Skip to main content

ark_di_flutter 1.3.0 copy "ark_di_flutter: ^1.3.0" to clipboard
ark_di_flutter: ^1.3.0 copied to clipboard

Flutter scopes and BuildContext access for Ark DI dependency containers.

Ark DI Flutter #

Flutter scope and BuildContext integration for Ark DI.

Ark DI Flutter connects an existing DiContainer hierarchy to the widget tree. It owns no global container, performs no reflection, and does not turn dependency injection into state management. Application objects continue to receive dependencies through constructors; widgets use the container at explicit composition boundaries.

Русская версия

This guide includes cached feature scopes, resolver-only boundaries and the Context API available since 1.2, alongside the original root/child scope API.

Version 1.3 adds opt-in memory-pressure cleanup at the cache owner's boundary, without changing the existing scope and ownership contracts.

Installation #

Build applications with a patched stable SDK: Dart 3.13.7+ or Flutter 3.47.8+. Package SDK constraints describe API compatibility, not the security of older runtimes. After the eMudhra incident, affected applications must be rebuilt and redistributed; updating a library alone is not enough. See the SDK security guidance.

dependencies:
  ark_di: ^1.3.0
  ark_di_flutter: ^1.3.0
import 'package:ark_di/ark_di.dart';
import 'package:ark_di_flutter/ark_di_flutter.dart';

Root scope #

Build the application container at the Composition Root and expose it above the application:

final DiContainer application = DiContainer.build((binder) {
  binder.bindLazySingleton<ApiClient>(
    (resolver) => ApiClient(),
    dispose: (client) => client.close(),
  );
});

runApp(
  DiRootScope(
    container: application,
    child: const Application(),
  ),
);

DiRootScope owns its container by default and starts close() when the widget stops exposing it. Use DiScopeOwnership.external when another object controls the root lifecycle.

Because Flutter disposal is synchronous while DiContainer.close() is asynchronous, closing continues without blocking the widget tree. Supply onCloseError to receive teardown failures. Without a handler, failures are reported through the Zone active when closing starts.

Child scope #

DiScope creates and owns a real child container. Missing dependencies fall back through the Ark DI parent hierarchy:

DiScope(
  configure: (binder) {
    binder.bindInstance<FeatureId>(featureId);
    binder.bindLazySingleton<FeaturePresenter>(
      (resolver) => FeaturePresenter(
        repository: resolver.get<UserRepository>(),
        featureId: resolver.get<FeatureId>(),
      ),
      dispose: (presenter) => presenter.close(),
    );
  },
  child: const FeatureScreen(),
)

The configuration callback is required and runs once for each parent-container identity. Ark DI registrations are immutable after creation. Give DiScope a new Key when changed configuration must create a fresh scope.

BuildContext access #

final UserRepository repository = context.readDi.get<UserRepository>();
final Session session = await context.readDi.getAsync<Session>();

Container access has four accessors; resolver-only access is described below:

Accessor Subscribes to scope replacement Missing scope
context.di Yes Throws DiScopeNotFoundException
context.maybeDi Yes Returns null
context.readDi No Throws DiScopeNotFoundException
context.maybeReadDi No Returns null

Use di from build or didChangeDependencies when the widget must follow a replacement scope. Use readDi for one-off event-handler access. Do not cache a container retrieved from BuildContext for later lifecycle callbacks.

Resolver-only access #

Use context.diResolver in build when replacement of the nearest resolver boundary should rebuild the consumer. Use context.readDiResolver for one-off event handlers. Their optional counterparts are maybeDiResolver and maybeReadDiResolver.

DiResolverScope(resolver: source, child: ...) exposes resolution without giving descendants container administration. It does not own or close the source. At this boundary context.di and readDi throw DiContainerAccessDeniedException; optional container lookups return null. An unavailable inner resolver boundary never falls back to an outer root. These accessors follow scope identity, not changes inside business objects.

Retain a local feature between screen visits #

Use an ordinary DiScope when leaving the feature should close its graph. Use DiCachedScope<A> when its managed data/state should survive temporary removal from the widget tree without becoming global.

The application/session owner creates a DiScopeCache with explicit capacity and idle TTL. It also creates stable DiScopeDefinition<A> values. Pass the same definition and immutable arguments on reopening. Do not create a new definition inside every build: definition identity is part of the cache key.

DiCachedScope<int>(
  cache: cache,
  definition: cartDefinition,
  viewDefinition: screenDefinition,
  arguments: 7,
  onCloseError: reportCloseError,
  builder: (
    final BuildContext context,
    final AsyncSnapshot<DiResolver> snapshot,
  ) {
    if (snapshot.hasError) {
      return const Text('Cart unavailable');
    }
    return snapshot.hasData
        ? const CartScreen()
        : const Text('Preparing cart');
  },
)

Here cartDefinition describes retained feature data, while optional screenDefinition describes a fresh owned child for that particular screen. Include every public type/key used by the screen in its expose allowlist, including permitted inherited registrations.

The builder runs under a resolver-only boundary. snapshot.data and context.readDiResolver provide its resolver; context.readDi intentionally does not. Put dependency reads below the ready state, not before it. Handle waiting and error states instead of treating every frame as ready.

What closes, and what remains #

  1. Mounting acquires a lease of the cached feature. A ready hit has no artificial waiting frame; cold acquisition can wait.
  2. With viewDefinition, mounting creates a separate noncached owned child. Put screen controllers there, not in retained feature state.
  3. Unmounting revokes screen access, closes the view child and releases the lease. It does not immediately destroy a feature another lease still uses.
  4. Once unused, the feature remains until idle TTL or eviction. Reopening can reuse the same managed instances and state.
  5. The owning session closes/invalidate its cache on logout or account changes. Closing the root also closes its owned caches. GC is not the cleanup policy.

Changed cache, definition identity or argument value ends the old access and selects the new feature. Changing only viewDefinition recreates the view child, not a still-active feature. Late acquire completions after unmount are released; they are not published to a removed screen. Invalidation produces an unavailable state rather than silently reacquiring privileged access.

Supply onCloseError for teardown failures and onRollbackError for secondary view-setup cleanup failures. Flutter cannot await widget disposal; the cache/root owner can await final close. Retention does not pause network work, refresh data, persist across process restarts or automatically rebuild UI when data changes.

The complete cached-cart application owns its root/cache/definitions, preserves an item count across close/reopen, and recreates/disposes its screen controller separately. It uses ValueListenableBuilder to observe the counter; DI itself is not the observer.

The cart uses the memory-pressure API available since 1.3. Use the example source as lib/main.dart in a Flutter application with the dependencies above and run flutter run there. This package directory has no platform runner projects.

For exact cache ownership, capacity and eviction rules see retained scopes. For typed modules, runtime/cache snapshots, setup rollback and the separate ark_di_test fixtures see composition and diagnostics.

Release idle scopes under memory pressure #

Available since 1.3.0.

A cart can remain cached after its screen closes. If Flutter reports memory pressure, the application may prefer releasing that idle graph over preserving its in-memory state. Opt in once at the cache owner's boundary:

DiScopeCacheMemoryPressure(
  cache: cache,
  onTrimError: (final Object error, final StackTrace stackTrace) {
    FlutterError.reportError(
      FlutterErrorDetails(exception: error, stack: stackTrace),
    );
  },
  child: const FeatureHost(),
)

Keep this widget mounted above the conditional screen or route subtree. Placing it inside DiCachedScope would remove the observer just when the graph becomes idle. It borrows the cache; it does not close it, expose a DI container to descendants or choose a logout/refresh policy.

  • A signal calls the existing trimIdle() policy: live consumer leases and view-child pins protect their graphs. A later signal can trim a newly idle graph.
  • Eviction destroys retained in-memory state. Reopening builds a fresh graph; this is neither persistence nor a guarantee that the OS will deliver a warning.
  • Repeated signals coalesce and trim passes do not overlap. Each pass starts on the next event turn so pending acquisition continuations can install leases.
  • enabled: false, removal or a changed cache detaches the old observer. Already-started cleanup finishes; no new old-observer passes are admitted.
  • onTrimError receives cleanup errors. Without it, errors go to the Zone captured at observer attachment. Reporter failures reach that same Zone; waiting for a reporter does not block later trim passes.

See the complete memory-pressure guide and the tested cart source linked above for ownership, shutdown and failure cases.

Opt-in Service Locator #

The main library contains no Service Locator. Compatibility for applications that explicitly require one is isolated behind another import:

import 'package:ark_di_flutter/service_locator.dart';

abstract final class ApplicationDependencies {
  static final DiServiceLocator locator = DiServiceLocator();
}

DiServiceLocator is an ordinary object. The package creates no global or static instance. attach and detach are explicit, and the locator never owns or closes the attached container.

Scope boundaries #

Ark DI Flutter handles widget-tree placement, child-scope lifetime, context lookup, and close-error delivery. It does not manage UI state, rebuild widgets when dependency data changes, create Presenters automatically, or discover dispose() methods by convention.

See the runnable example and the Ark DI architecture guide.

AI agent skill #

The package ships ark-di-flutter-scopes, a version-matched skill for root and feature scopes, BuildContext access, ownership, close errors, and the opt-in locator adapter.

dart run skills@ get -p ark_di_flutter

Review installed instructions before use and keep application composition rules in project-owned files.

Roadmap #

Version 1.2 includes resolver-only boundaries, explicit Context access and opt-in cached feature scopes with per-view ownership. Core runtime/cache diagnostics and typed composition are shared from Ark DI; test fixtures live in the separate ark_di_test package.

Version 1.3 adds opt-in memory-pressure integration. Additional host adapters remain deferred; ordinary scope ownership does not change implicitly.

License #

Apache License 2.0. See LICENSE and NOTICE.

0
likes
160
points
520
downloads

Documentation

Documentation
API reference

Publisher

verified publisherarktelos.dev

Weekly Downloads

Flutter scopes and BuildContext access for Ark DI dependency containers.

Homepage
Repository (GitLab)
View/report issues

Topics

#architecture #dependency-injection #flutter #inversion-of-control

License

Apache-2.0 (license)

Dependencies

ark_di, flutter

More

Packages that depend on ark_di_flutter