Flutter
Release idle scopes
Release idle scopes explicitly while protecting active screens and understanding which state is lost.
Available in Ark DI Flutter 1.3.0 and later.
The core cache API is unchanged; this adapter uses DiScopeCache.trimIdle().
The problem this solves
A local cart, editor or catalogue scope may remain cached after its screen closes. Reopening it can reuse the existing objects and state. Keeping every recent feature alive is not always worth the memory, even before its idle TTL expires. The cache owner can opt into releasing unused graphs when Flutter reports memory pressure.
This is a trade-off: the evicted graph's in-memory state is lost. Do not keep the only copy of an unsaved draft or purchase in a disposable cache. Persist important state in the application layer independently of DI retention.
Put the observer beside the cache owner
The owner creates a stable cache and definitions, as in the complete cart example. Wrap the feature host once, outside its conditional screen subtree:
DiScopeCacheMemoryPressure(
cache: cache,
enabled: allowIdleStateLoss,
onTrimError: (final Object error, final StackTrace stackTrace) {
FlutterError.reportError(
FlutterErrorDetails(exception: error, stack: stackTrace),
);
},
child: const FeatureHost(),
)
Import package:ark_di_flutter/ark_di_flutter.dart and Flutter's
package:flutter/widgets.dart. allowIdleStateLoss is an application setting,
not a package-provided global. Omit enabled to observe while mounted.
The structure is:
Application/session owner: owns root, cache and stable definitions
└─ DiScopeCacheMemoryPressure: borrows cache, observes system signals
└─ FeatureHost: decides whether the screen is present
└─ DiCachedScope: owns a lease and optional per-view child
Putting the observer inside DiCachedScope defeats idle cleanup after that
screen disappears. Create one observer per cache owner, not one per screen
sharing the cache. The widget does not provide a resolver or expose container
administration. Descendants still use the appropriate DI boundary.
What happens after a signal
- The observer schedules a trim on the next event turn. Already pending Dart microtasks can finish delivering acquisition leases before idle selection.
trimIdle()selects unused graphs. A live consumer lease or view-child pin protects a graph. Releasing one of several consumers is not enough.- Selected graphs retire and run their existing DI disposal sequence. Separate graphs may close concurrently within that pass; dependency-order rules inside each graph are unchanged.
- Successful retirement removes the graph. The next acquisition creates new instances. A protected active graph keeps its instances and state.
Repeated signals before a pass starts coalesce. Signals during a pass request at most one pending follow-up pass, which also starts on the next event turn. The observer never overlaps its own trim passes. If a feature becomes idle after the last pass, normal TTL/capacity rules still apply; it is not trimmed again unless a new signal or another cache operation requires it.
An already retiring generation may have been invalidated explicitly by the
owner. trimIdle() joins that cleanup; it does not reverse owner invalidation
or restore revoked access. A new acquisition waiting for retirement continues
through the cache's existing rules.
Enable, replace and remove
enabled: false stops observation without replacing the child subtree or
closing the cache. Re-enabling attaches a new observer; it does not replay old
signals or immediately trim.
Changing the cache detaches the old observer and observes the new cache.
Removing the widget detaches its observer. Pending follow-up requests are
dropped. A pass that has already called trimIdle() finishes normally: it
cannot undo retirement or cancel arbitrary application disposers.
The application/session owner still closes the cache or root at the end of its lifetime. An externally closed cache is an ordinary end of observation, not a trim error. The widget does not perform logout, refresh data, pause network work or infer whether business objects are still useful.
Handle cleanup errors
The cache aggregates disposal failures into DiCloseException; the observer
passes the error and its stack to onTrimError. Each pass captures the handler
before starting, so an old in-flight pass keeps its original handler even if
the widget or cache is replaced. Do not depend on a removed widget's context
in that handler; use an application-owned error sink.
The handler can return void or Future<void>. Its completion does not block
future trims. Without a handler, failures reach the Zone captured when the
observer was attached. Synchronous or asynchronous handler failures reach the
same Zone. Errors are not silently discarded and disposal is not retried
automatically. The owner's final close() errors remain the owner's concern;
onTrimError is not a replacement for observing them.
There is no timeout or cancellation of arbitrary disposers. A disposer that never completes keeps that observer's trim pass pending. Design disposal to finish and handle external service timeouts at the relevant application boundary.
Try it and verify the boundary
The cart source uses only Flutter widgets, not Material or Cupertino. It
demonstrates retained data separately from a per-screen controller. To launch
it, use its source as lib/main.dart in a Flutter application with
ark_di_flutter: ^1.3.0 and ark_di: ^1.3.1, then run flutter run there.
The package itself contains no platform runner project.
Run the repository checks from this package directory:
flutter test test/memory_pressure_test.dart test/cached_feature_example_test.dart
Tests dispatch tester.binding.handleMemoryPressure() and advance the event
queue. They check active consumers, view pins, pending acquisitions, eviction,
invalidation, cache replacement, disabling, unmounting, shutdown and errors.
The cart checks that an open cart survives and an idle cart starts fresh.
These are simulated framework signals, not physical-device OOM tests or
measurements of bytes reclaimed.
Flutter exposes this signal through
WidgetsBindingObserver.didHaveMemoryPressure.
It is advisory: it does not guarantee a warning before process termination,
immediate garbage collection or return of a particular amount of RAM to the OS.