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.

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.2.1
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.

flutter run example/cached_feature.dart

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.

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.

Additional host adapters and automatic memory-pressure integration remain deferred; they do not change ordinary scope ownership implicitly.

License

Apache License 2.0. See LICENSE and NOTICE.

Libraries

ark_di_flutter
Flutter scope integration for Ark DI dependency containers.
service_locator
Opt-in Service Locator compatibility for Ark DI applications.