Tutorials
A cart with a cached scope
A runnable Flutter application with retained cart data and separately owned screen controllers.
Run it and observe the lifetime
Create a normal Flutter application, add the dependencies and replace lib/main.dart with the code below. No Material/Cupertino package is required.
flutter pub add ark_di:^1.3.1 ark_di_flutter:^1.3.0
flutter run
Tap Add item, then Close cart and Open cart. The count remains 1: the feature stayed local, but its lease was returned to the cache. The screen's TextEditingController belongs to a separate view child and is created again.
import 'dart:async';
import 'package:ark_di/ark_di.dart';
import 'package:ark_di_flutter/ark_di_flutter.dart';
import 'package:flutter/widgets.dart';
void main() => runApp(const CachedCartExample());
/// Opens and closes a cart while retaining its data, not its screen objects.
final class CachedCartExample extends StatefulWidget {
const CachedCartExample({super.key});
@override
State<CachedCartExample> createState() => _CachedCartExampleState();
}
final class _CachedCartExampleState extends State<CachedCartExample> {
late final DiContainer _application;
late final DiScopeCache _cache;
late final DiScopeDefinition<int> _cart;
late final DiScopeDefinition<int> _view;
bool _visible = true;
@override
void initState() {
super.initState();
_application = DiContainer.build((final DiBinder binder) {});
_cache = _application.createScopeCache(
policy: const DiScopeCachePolicy(
maxScopes: 2,
idleTimeout: Duration(minutes: 5),
),
);
_cart = DiScopeDefinition<int>(
configure: (final DiBinder binder, final int cartId) =>
binder.bindLazySingleton<_CartCount>(
(final DiResolver resolver) => _CartCount(),
dispose: (final _CartCount counter) => counter.dispose(),
),
expose: (final int cartId) => <DiDependencyDescriptor>[
const DiDependencyDescriptor(type: _CartCount),
],
);
_view = DiScopeDefinition<int>(
configure: (final DiBinder binder, final int cartId) =>
binder.bindLazySingleton<TextEditingController>(
(final DiResolver resolver) =>
TextEditingController(text: 'New screen controller'),
dispose: (final TextEditingController controller) =>
controller.dispose(),
),
expose: (final int cartId) => <DiDependencyDescriptor>[
const DiDependencyDescriptor(type: _CartCount),
const DiDependencyDescriptor(type: TextEditingController),
],
);
}
@override
void dispose() {
// Flutter cannot await dispose. The owner still observes close failures.
unawaited(_application.close().catchError(_reportCloseError));
super.dispose();
}
void _reportCloseError(final Object error, final StackTrace stackTrace) =>
FlutterError.reportError(
FlutterErrorDetails(exception: error, stack: stackTrace),
);
@override
Widget build(final BuildContext context) => Directionality(
textDirection: TextDirection.ltr,
// Keep the observer mounted even while the cart screen is absent.
child: DiScopeCacheMemoryPressure(
cache: _cache,
onTrimError: _reportCloseError,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Semantics(
button: true,
child: GestureDetector(
onTap: () => setState(() => _visible = !_visible),
child: Text(_visible ? 'Close cart' : 'Open cart'),
),
),
if (_visible)
DiCachedScope<int>(
cache: _cache,
definition: _cart,
viewDefinition: _view,
arguments: 7,
onCloseError: _reportCloseError,
builder:
(
final BuildContext context,
final AsyncSnapshot<DiResolver> snapshot,
) => snapshot.hasError
? const Text('Cart unavailable')
: snapshot.hasData
? const _CartView()
: const Text('Preparing cart'),
)
else
const Text(
'Cart closed; data may be released on memory pressure or expiry',
),
],
),
),
),
);
}
final class _CartCount extends ValueNotifier<int> {
_CartCount() : super(0);
void addItem() => value++;
}
final class _CartView extends StatelessWidget {
const _CartView();
@override
Widget build(final BuildContext context) {
final DiResolver resolver = context.readDiResolver;
final _CartCount count = resolver.get<_CartCount>();
final TextEditingController controller = resolver
.get<TextEditingController>();
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ValueListenableBuilder<int>(
valueListenable: count,
builder:
(
final BuildContext context,
final int value,
final Widget? child,
) => Text('Items: $value'),
),
Text(controller.text),
Semantics(
button: true,
child: GestureDetector(
onTap: count.addItem,
child: const Text('Add item'),
),
),
],
);
}
}
Why it works
initState creates the root, cache and both definitions once. _cart owns the counter; _view owns the screen controller. DiCachedScope exposes a resolver only when ready and returns its lease on removal. The root owner observes asynchronous close during dispose.
Do not create a new definition on every build: that changes the cache key. Choose TTL/capacity for your feature; close the relevant cache on logout rather than waiting for TTL. The detailed rules cover errors, invalidation and late acquire completion.
Memory Pressure
The observer stays above the conditional cart screen. On memory pressure, an open cart keeps its count, while an idle cart can be released: the next opening starts at zero. This is intentional loss of temporary state, not a restore failure. The example has no button pretending to be an OS signal; the package widget test exercises that scenario. Setup and guarantee boundaries.