WeakReference<T extends Object> class

A weak reference to a Dart object.

A weak reference to the target object which may be cleared (set to reference null instead) at any time when there is no other way for the program to access the target object.

Being the target of a weak reference does not keep an object from being garbage collected.

There are no guarantees that a weak reference will ever be cleared even if all references to its target are weak references.

Not all objects are supported as targets for weak references. The WeakReference constructor will reject any object that is not supported as an Expando key.

Use-cases like caching can benefit from using weak references. Example:

/// [CachedComputation] caches the computation result, weakly holding
/// on to the cache.
///
/// If nothing else in the program is holding on the result, and the
/// garbage collector runs, the cache is purged, freeing the memory.
///
/// Until the cache is purged, the computation will not run again on
/// a subsequent request.
///
/// Example use:
/// ```
/// final cached = CachedComputation(
///     () => jsonDecode(someJsonSource) as Object);
/// print(cached.result); // Executes computation.
/// print(cached.result); // Most likely uses cache.
/// ```
class CachedComputation<R extends Object> {
  final R Function() computation;

  WeakReference<R>? _cache;

  CachedComputation(this.computation);

  R get result {
    final cachedResult = _cache?.target;
    if (cachedResult != null) {
      return cachedResult;
    }

    final result = computation();

    // WeakReferences do not support nulls, bools, numbers, and strings.
    if (result is! bool && result is! num && result is! String) {
      _cache = WeakReference(result);
    }

    return result;
  }
}
Annotations
  • @Since("2.17")

Constructors

WeakReference(T target)
Creates a WeakReference pointing to the given target.
factory

Properties

hashCode int
The hash code for this object.
read-onlyinherited
runtimeType Type
A representation of the runtime type of the object.
read-onlyinherited
target → T?
The current object weakly referenced by this, if any.
read-only

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited