weak method
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
checkWeakRefTargetistrue(default), readsWeakReference.targetand returns the object if still reachable - If the object was already collected, clears the weak reference
and returns
null - If
checkWeakRefTargetisfalse, does not access the weak reference and returnsnull
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;
}