weak method

T? weak({
  1. bool checkWeakRefTarget = true,
})

Converts this reference into a weak reference.

If currently strong:

  • Releases the strong reference
  • Creates a WeakReference if one does not already exist
  • Notifies the manager that this reference is no longer strong
  • Returns the target object

If already weak:

  • No state change occurs
  • If checkWeakRefTarget is true (default), reads WeakReference.target and returns the object if still reachable
  • If the object was already collected, clears the weak reference and returns null
  • If checkWeakRefTarget is false, does not access the weak reference and returns null

Implementation

T? weak({bool checkWeakRefTarget = true}) {
  var ref = _strongRef;
  if (ref != null) {
    _strongRef = null;
    // If a weak reference already exists, it points to `ref`
    // since the strong reference keeps it alive.
    // Only create it if missing:
    _weakRef ??= WeakReference(ref);

    // New weak reference, handle it:
    _manager?._handleNewWeakRef(this);
    assert(!_queued);
    return ref;
  }

  // Avoid checking `_weakRef.target`:
  if (!checkWeakRefTarget) {
    return null;
  }

  ref = _weakRef?.target;
  if (ref == null) {
    // Lost reference, not reachable either strongly or weakly:
    _weakRef = null;
  }

  return ref;
}