Dart WeakReference & Finalizer: When You Want to Remember Without Owning
Every once in a while, Dart gives you a feature that is less about everyday app development and more about the language’s relationship with memory.
Expando was one of those features. WeakReference and Finalizer live in the same neighborhood, but they solve different problems.
They are not state management tools. They are not replacements for dispose(). They are not something you should casually sprinkle through Flutter widgets.
They are lower-level runtime tools for one very specific family of problems:
How do I observe, cache, or clean up around an object without accidentally becoming the reason that object stays alive?
In this article, we’ll look at what WeakReference and Finalizer are, how they work, where they earn their keep, and why most app code should still prefer explicit ownership and cleanup.
The problem: strong references own things
In Dart, a normal reference is a strong reference.
class Document {
final String path;
Document(this.path);
}
final documents = <Document>[];
void openDocument(String path) {
final document = Document(path);
documents.add(document);
}
As long as documents contains the Document, that document is alive.
documents ──► Document("notes.md")
The garbage collector cannot collect it because the list can still reach it.
Most of the time, this is exactly what you want. If something is in your list, map, field, cache, or service, you expect it to stay there.
But sometimes you want something weaker:
"I want to remember this object if it is still alive,
but I don't want my memory of it to keep it alive."
That is WeakReference.
And sometimes you want this:
"When this object is forgotten, please clean up something else eventually."
That is Finalizer.
What is WeakReference?
Here’s the short version:
A WeakReference points to an object without keeping that object alive.
final document = Document('notes.md');
final weakDocument = WeakReference(document);
A normal reference looks like this:
strong ──► document
A weak reference looks like this:
weak - - -► document
The dashed arrow is the important part. It lets you ask for the object, but it does not protect the object from garbage collection.
You read the target like this:
final document = weakDocument.target;
If the object is still alive, you get it back. If the object has been garbage collected, you get null.
So the mental model is:
WeakReference<T>
└── target: T?
Not because T is nullable, but because the runtime is allowed to clear the weak reference when the target is no longer strongly reachable.
Basic usage
Here’s a small example:
class UserSession {
final String id;
UserSession(this.id);
@override
String toString() => 'UserSession($id)';
}
void main() {
var session = UserSession('user-123');
final weakSession = WeakReference(session);
print(weakSession.target); // UserSession(user-123)
// Remove the strong reference.
session = UserSession('user-456');
// At some later point, after GC, the old target may be gone.
print(weakSession.target); // UserSession(user-123) or null
}
Notice the careful wording: may be gone.
Garbage collection is nondeterministic. The old session becomes eligible for collection when nothing strongly references it, but that does not mean it disappears immediately.
This is one of the most important things to understand about weak references:
A weak reference is not a timer, not a lifecycle callback, and not a guarantee that
targetbecomesnullas soon as your variable goes out of scope.
It only means the weak reference itself is not enough to keep the object alive.
Why not just use a Map?
Suppose you are building a document editor. Users can open and close files. Parsing a document into an AST is expensive, so you add a cache.
final parsedDocuments = <String, ParsedDocument>{};
ParsedDocument parseDocument(String path, String source) {
final cached = parsedDocuments[path];
if (cached != null) return cached;
final parsed = ParsedDocument.parse(path, source);
parsedDocuments[path] = parsed;
return parsed;
}
This works, but the cache strongly owns every parsed document.
parsedDocuments
└── "notes.md" ──► ParsedDocument
Even if the user closes notes.md, your cache keeps the parsed tree alive forever unless you remember to manually remove it.
That may be fine if this is an LRU cache with a size limit. But if your goal is:
Reuse the parsed document if something else is already keeping it alive,
but don't keep it alive just because it was parsed once.
then a normal Map<String, ParsedDocument> is too strong. Use a weak cache instead:
class ParsedDocumentCache {
final _cache = <String, WeakReference<ParsedDocument>>{};
ParsedDocument parse(String path, String source) {
final cached = _cache[path]?.target;
if (cached != null) return cached;
final parsed = ParsedDocument.parse(path, source);
_cache[path] = WeakReference(parsed);
return parsed;
}
void compact() {
_cache.removeWhere((_, weak) => weak.target == null);
}
}
Now the map strongly holds the weak reference, but the weak reference does not strongly hold the parsed document.
_cache
└── "notes.md" ──► WeakReference - - -► ParsedDocument
If the editor tab, model, or analysis pipeline still strongly references the parsed document, the cache can reuse it. If nobody else references it, the parsed document can be collected.
This cache is intentionally soft. It says:
If a parsed document is still alive somewhere else, reuse it.
If not, don't keep it alive just for me.
The compact() method is still needed because the map accumulates dead WeakReference wrappers. The parsed documents can be gone, but the map entries remain until you remove them.
That is an important practical detail:
Weak references stop values from being kept alive. They do not automatically clean up your map keys.
Where else weak references earn their keep
The document cache is one instance of a shape that shows up all over infrastructure code:
- Debug and plugin registries. A “last seen instance” registry for plugins or services should be able to hand back an instance if it is still loaded, without becoming the reason it can never unload. Observation should not become ownership.
- Image and thumbnail caches. Decoding is expensive, but a weak cache only reuses thumbnails that a visible screen or active request is already keeping alive. If the answer to a cache miss is “regenerate it”, a weak cache fits. If regenerating is unacceptable, use a real cache with explicit eviction.
- Deduplication tables. Hand back the existing instance when one is alive; let it go when nobody cares.
The common thread: the cache or registry is a convenience layer, never an owner. Weak caches are opportunistic, not authoritative.
A practical pattern: weak-value cache
If you use weak references in a map, hide the cleanup logic behind an API.
class WeakValueCache<K, V extends Object> {
final _entries = <K, WeakReference<V>>{};
V? operator [](K key) {
return _entries[key]?.target;
}
void operator []=(K key, V value) {
_entries[key] = WeakReference(value);
}
V putIfAbsent(K key, V Function() create) {
final existing = this[key];
if (existing != null) return existing;
final value = create();
this[key] = value;
return value;
}
void compact() {
_entries.removeWhere((_, weak) => weak.target == null);
}
void clear() {
_entries.clear();
}
}
Usage:
final thumbnails = WeakValueCache<String, Thumbnail>();
Thumbnail thumbnailFor(String path) {
return thumbnails.putIfAbsent(path, () {
return generateThumbnail(path);
});
}
This keeps the weak-reference weirdness contained.
That is usually a good rule:
If you use weak references, hide them behind a purpose-built type.
Where WeakReference can bite you
1. Weak means maybe gone
This is not safe:
final value = weak.target!;
value.doSomething();
The whole point of WeakReference is that target can be null. Always treat it as optional:
final value = weak.target;
if (value == null) {
// Recreate, reload, or skip.
} else {
value.doSomething();
}
And if your app only works when target is non-null, the design is wrong. Weak references are for optional reuse, not required ownership.
2. GC timing is not deterministic
This is not a reliable test:
var object = Object();
final weak = WeakReference(object);
object = Object();
print(weak.target); // May still be non-null.
The old object is eligible for collection, but the runtime does not have to collect it immediately.
3. The map still strongly holds its keys
WeakReference weakens the value it points to. It does not magically make your whole data structure weak.
final _adapters = <Schema, WeakReference<JsonAdapter>>{};
Here the adapters are weakly held, but every Schema key is strongly held by the map:
_adapters
└── key: Schema ──► keeps Schema alive
If that is not what you want, key by a stable ID instead:
final _adapters = <String, WeakReference<JsonAdapter>>{};
And even with cheap keys, the map accumulates dead entries — keys and empty wrappers — so it can still grow forever without an occasional compact().
4. Closures can quietly make the object strong again
This is a classic bug:
void register(Object owner) {
final weak = WeakReference(owner);
someCallbacks.add(() {
print(owner); // Oops. This captures owner strongly.
});
}
You created a weak reference, but the closure captured the original object, so it is still strongly reachable.
Better:
void register(Object owner) {
final weak = WeakReference(owner);
someCallbacks.add(() {
final target = weak.target;
if (target == null) return;
print(target);
});
}
Any closure, stream subscription, timer, or callback that captures the object defeats the weak reference. Keep this one in mind — it comes back to haunt finalizers too.
5. It can hide ownership bugs
Sometimes a weak reference is the right answer. Sometimes it is just avoiding the harder question:
Who actually owns this object?
If there is a clear owner, use a normal strong reference.
What is Finalizer?
WeakReference lets you ask:
Is this object still alive?
Finalizer lets you say:
When this object becomes unreachable, eventually call this cleanup callback.
The official Dart docs describe Finalizer as a way to clean up an external connection when the user of an API no longer has access to that connection.
That “external” part is important. Finalizers are most useful when a Dart object is a wrapper around something outside normal Dart memory: native handles, database connections, file descriptors, temporary directories, registrations in another system.
Dart’s garbage collector understands Dart objects. It does not automatically know what to do with a file descriptor, native pointer, or registration in some external service.
A finalizer can be your safety net.
Basic usage: object, token, detach key
A finalizer has a callback, and you attach it to an object:
final finalizer = Finalizer<String>((token) {
print('Cleaning up $token');
});
final object = Object();
finalizer.attach(
object,
'resource-id-123',
detach: object,
);
Conceptually:
object becomes unreachable
→ sometime later
→ finalizer callback receives "resource-id-123"
Three things are in play here, and they have distinct jobs:
1. The attached object — the object whose lifetime you want to observe. When it becomes unreachable, the finalizer may run.
2. The finalization token — the value passed to the callback. It should contain enough information to clean up, but it should not keep the attached object alive.
3. The detach key — the thing you use to cancel the finalizer if you clean up manually:
finalizer.detach(this);
A common pattern is finalizer.attach(this, handle, detach: this). The docs explicitly allow the attached object and detach key to be the same object; being a detach key does not keep the object alive.
The finalizer rule you must not break
Never use the attached object itself as the finalization token.
This is bad:
final finalizer = Finalizer<Resource>((resource) {
resource.close();
});
class Resource {
Resource() {
finalizer.attach(this, this, detach: this);
}
void close() {}
}
Why? Because the finalizer holds the token strongly.
finalizer ──► token
token == this
therefore finalizer ──► this
So the object never becomes unreachable. Which means the finalizer never runs.
You built a self-preventing finalizer.
The token should be separate from the object being watched.
A real example: a database session with a safety net
Imagine you are writing a small backend package around a database connection pool.
You already have close(). Users should call it. But if they forget, you want a last-resort cleanup so the underlying connection can be returned or closed eventually.
class DriverConnection {
final int id;
DriverConnection(this.id);
void close() {
print('Closing driver connection $id');
}
}
final _connectionFinalizer = Finalizer<DriverConnection>((connection) {
connection.close();
});
class DatabaseSession {
DatabaseSession(this._connection) {
_connectionFinalizer.attach(
this,
_connection,
detach: this,
);
}
final DriverConnection _connection;
bool _closed = false;
Future<void> query(String sql) async {
if (_closed) {
throw StateError('DatabaseSession is already closed.');
}
print('Running query on connection ${_connection.id}: $sql');
}
void close() {
if (_closed) return;
_closed = true;
_connectionFinalizer.detach(this);
_connection.close();
}
}
This is still the correct API: explicit cleanup.
Future<void> handleRequest() async {
final session = DatabaseSession(DriverConnection(42));
try {
await session.query('select * from users');
} finally {
session.close();
}
}
The finalizer is only there for this mistake:
Future<void> badRequestHandler() async {
final session = DatabaseSession(DriverConnection(42));
await session.query('select * from users');
// Forgot session.close().
}
At some later point, if the DatabaseSession becomes unreachable, the finalizer may close the underlying connection. That “may” is why finalizers are a safety net, not your lifecycle.
The whole pattern fits in three lines:
constructor:
attach finalizer
close/dispose:
detach finalizer
clean up manually
finalizer:
backup cleanup if dispose was forgotten
The same shape works anywhere a Dart object fronts an external resource: a CLI tool’s temporary working directory that should be deleted, a subscription that must be unregistered from an external event bus or engine, a handle checked out from some registry. Attach in the constructor, detach in the explicit cleanup, let the finalizer be the backup.
One warning that carries over from weak references: if the resource’s callback captures the wrapper object — an event handler that prints its own subscription, say — the wrapper never becomes unreachable and the finalizer never runs. Finalizer code is full of traps like this.
Native resources and NativeFinalizer
The classic finalizer use case is FFI.
Dart can wrap native memory or native handles, but Dart’s GC does not automatically know how to free C memory. For this, Dart has NativeFinalizer, which is designed for native cleanup callbacks.
A simplified shape looks like this:
import 'dart:ffi';
final class NativeImage extends Finalizable {
NativeImage(this.pointer) {
_finalizer.attach(
this,
pointer.cast<Void>(),
detach: this,
);
}
final Pointer<Void> pointer;
static final _finalizer = NativeFinalizer(_nativeFree);
void dispose() {
_finalizer.detach(this);
_nativeFree.asFunction<void Function(Pointer<Void>)>()(pointer);
}
}
external Pointer<NativeFunction<Void Function(Pointer<Void>)>> get _nativeFree;
This is only a sketch, because real FFI code depends on how you load your native library and how the native free function is exposed. The pattern is the part that matters — and it is the same attach/detach/backup pattern as before.
If you are working with FFI, reach for NativeFinalizer, not plain Finalizer, when you need native callback cleanup.
Finalizer is not dispose
Let’s say it plainly:
Finalizer is not a replacement for
dispose(),close(),cancel(), ordelete().
Garbage collection happens when the runtime decides it needs to happen. Your object becoming unreachable does not mean the callback runs now. It means:
object is eligible for collection
→ at some later GC
→ finalizer may be scheduled
→ callback may run
Later. Much later. Or not before process exit.
So this is wrong:
void handleRequest() {
final session = DatabaseSession(DriverConnection(1));
session.query('select * from users');
// "The finalizer will clean it up."
}
If something must happen — saving user data, committing a transaction, releasing a scarce resource on a strict timeline — do it deterministically with try/finally and explicit cleanup. Finalizers are for backup cleanup, not timely cleanup.
Where Finalizer can bite you
1. The callback may run late — or never
Finalizers are not timely, and they are not guaranteed to run before shutdown. If a resource must be released now, release it manually. Do not rely on finalizers to flush data or save important work.
2. The token can keep the object alive
finalizer.attach(this, this) is the self-preventing finalizer from earlier. Do not do it.
3. The callback should not depend on app state being valid
By the time a finalizer runs, the world may be different: the service may be shutting down, the isolate may be exiting, other objects may already be gone. Keep finalizer callbacks small and defensive.
4. Finalizers make tests tricky
You cannot write a clean unit test that says:
drop object
expect finalizer to run immediately
GC timing is not under your control. Test the explicit dispose() path. Treat finalizers as backup behavior.
WeakReference, Finalizer, and Flutter
For normal Flutter code, you still want this:
@override
void dispose() {
subscription.cancel();
controller.dispose();
animationController.dispose();
super.dispose();
}
Do not replace it with finalizers. Flutter controllers and subscriptions have deterministic lifecycles for a reason.
Where these tools may show up in Flutter-related code:
- image/cache infrastructure
- devtools/debug tooling
- plugin internals and FFI bindings
- framework-style packages
- large document/editor tooling
Most widgets and app screens should never need them.
When should you use WeakReference?
Reach for WeakReference when all of these are true:
- You want to remember an object only if something else keeps it alive.
- It is okay if the object disappears.
- You have a clear fallback when
targetisnull. - You are not using it to avoid real ownership.
- You have a plan to compact any maps or registries holding weak references.
Good fits:
- opportunistic caches
- debug registries
- plugin registries
- deduplication tables
Bad fits:
- required app state
- active subscriptions
- UI lifecycle
- anything that must not disappear
When should you use Finalizer?
Reach for Finalizer when all of these are true:
- A Dart object represents some external resource.
- That external resource should be cleaned up if the Dart object is forgotten.
- You already provide explicit cleanup.
- The finalizer is only a backup.
- The finalization token does not keep the attached object alive.
Good fits:
- native handles and FFI memory
- temporary directories
- external registrations
- defensive cleanup in packages
Bad fits:
- saving data
- closing critical resources on time
- business logic and UI disposal
- anything that must happen predictably
WeakReference vs Expando vs Finalizer
They are easy to confuse because all three involve the garbage collector. But they answer different questions.
| Tool | Main job | Keeps object alive? | Lets you retrieve object? | Runs callback? | Stores side data? |
|---|---|---|---|---|---|
| Expando | Attach metadata to an object | No, for the key | No | No | Yes |
| WeakReference | Point to object weakly | No | Yes, maybe | No | No |
| Finalizer | Cleanup after object dies | No, if used correctly | No | Eventually | No |
Their mental models:
Expando:
object → metadata
WeakReference:
weak handle - - -► maybe object
Finalizer:
object dies → eventually callback(token)
With Expando, you already have the object and want its side data. With WeakReference, you have the weak handle and want to know if the object still exists. With Finalizer, you never get the object back — you get a chance to clean up after it.
A weak reference does not notify you. A finalizer does not let you retrieve the object. One is for observation, one is for cleanup.
Same neighborhood. Different jobs.
What this article didn’t cover
A few things are worth their own rabbit hole:
- How WeakReference, Expando, and Finalizer are implemented inside the Dart VM.
- How weak processing interacts with generational garbage collection.
- NativeFinalizer in full FFI detail.
- How to test finalizer behavior without writing fragile tests.
None of that changes the practical advice:
Weak references are for optional memory-sensitive reuse. Finalizers are for backup cleanup. Neither is a replacement for clear ownership.
Summary
WeakReference and Finalizer are both about interacting with object lifetime without becoming the owner of that lifetime.
WeakReference:
"I want to find this object again if someone else kept it alive."
Finalizer:
"I want a cleanup callback if this object is eventually forgotten."
They are powerful because they work with the garbage collector. They are dangerous for the same reason.
Use them in infrastructure, libraries, caches, tools, and native bindings. Avoid them in everyday app state unless you have a very specific memory-lifetime problem and a clear reason normal ownership does not fit.
If your code needs something to happen at a predictable time, use
close(),dispose(),cancel(), ordelete(). If it only needs a safety net when someone forgets, then Finalizer might belong there.
If your cache owns the value, use a normal cache. If your cache should only remember the value while something else owns it, WeakReference might be the right tool.
Hope you enjoyed going one level deeper into Dart’s memory model.