Sub topic 12
Scoping Dependencies to a Feature or Session
This chapter assumes you know constructor injection, abstract classes, Provider basics, and get_it registration. It also assumes you know ChangeNotifier and how BuildContext finds ancestors in the widget tree. The earlier chapters registered everything once at startup and kept it until the app closed. That works for an HTTP client. It fails for an object that belongs to one signed-in user or one screen.
What a scope is
A scope is a region of the app's lifetime in which a set of dependencies exists. When the region ends, the dependencies are disposed. Most apps have three useful scopes:
- App scope: lives from launch to exit. Examples: the HTTP client, settings storage, the logger.
- Session scope: lives from login to logout. Examples: the current user, a user-specific cart repository, an authenticated API client.
- Feature scope: lives while one flow or screen is open. Examples: a checkout view model, a form draft.
The rule that keeps scopes safe
A dependency may depend on objects from its own scope or an outer (longer-lived) scope. It must never depend on an inner (shorter-lived) one.
If an app-scoped singleton holds a reference to a session-scoped CartRepository, that singleton keeps the old user's data alive after logout. The next user may then see it. Most scoping bugs in Flutter come from breaking this rule.
Why scope at all
- Data isolation. After logout, no object should still hold the previous user's token, cache, or cart.
- Resource cleanup. Streams, sockets, and timers owned by a feature should close when the feature closes.
- Memory. A lazy object created for one screen should not live forever.
- Testability. A scope boundary is a natural place to substitute fakes for a whole feature.
Scoping with Provider
Provider scopes by position. A provider is visible only to its descendants, and it is disposed when its widget leaves the tree. You choose the scope by choosing where to place the provider.
Session scope
The widget below creates the session objects and keys them to the user. When the user ID changes, the key changes. Flutter then discards the old provider state and builds new state.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Session {
Session(this.userId);
final int userId;
}
class CartRepository {
CartRepository(this.session);
final Session session;
final List<String> items = [];
void dispose() => items.clear();
}
class SessionScope extends StatelessWidget {
const SessionScope({super.key, required this.session, required this.child});
final Session session;
final Widget child;
@override
Widget build(BuildContext context) {
return MultiProvider(
key: ValueKey(session.userId),
providers: [
Provider<Session>.value(value: session),
Provider<CartRepository>(
create: (context) => CartRepository(context.read<Session>()),
dispose: (_, repository) => repository.dispose(),
),
],
child: child,
);
}
}Place SessionScope below your authentication check, for example as the root of the signed-in part of the app. On logout the app shows the login screen. SessionScope leaves the tree, and dispose runs on the repository.
Provider.value does not dispose the value, because it did not create it. Use the create and dispose pair for objects the provider owns.
Feature scope
For a single flow, put the provider in the route that opens it.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class CheckoutViewModel extends ChangeNotifier {
CheckoutViewModel(this._cart);
final CartRepository _cart;
int get itemCount => _cart.items.length;
}
void openCheckout(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => ChangeNotifierProvider<CheckoutViewModel>(
create: (routeContext) =>
CheckoutViewModel(routeContext.read<CartRepository>()),
child: const CheckoutPage(),
),
),
);
}
class CheckoutPage extends StatelessWidget {
const CheckoutPage({super.key});
@override
Widget build(BuildContext context) {
final count = context.watch<CheckoutViewModel>().itemCount;
return Scaffold(body: Center(child: Text('Items: $count')));
}
}CheckoutViewModel exists only while the route is on the stack. ChangeNotifierProvider calls dispose() on it when the route is popped. The route can still read CartRepository, because the route sits under SessionScope. This code uses the classes from the previous block.
A route pushed with Navigator is a child of the Navigator, not of the widget that called push. Any provider you want the route to see must sit above the Navigator, which usually means above MaterialApp. A provider created inside one screen is not visible to a route pushed from that screen. Put the provider in the route's builder, as shown, or lift it higher.
Scoping with get_it
get_it has no widget tree, so it needs explicit scopes. pushNewScope creates a new layer of registrations. Registrations in the new layer shadow older ones with the same type. popScope removes the layer and runs the dispose callbacks of what it held.
import 'package:get_it/get_it.dart';
final getIt = GetIt.instance;
void onLogin(int userId) {
getIt.pushNewScope(
scopeName: 'session',
init: (scope) {
scope.registerSingleton<Session>(Session(userId));
scope.registerLazySingleton<CartRepository>(
() => CartRepository(scope<Session>()),
dispose: (repository) => repository.dispose(),
);
},
);
}
Future<void> onLogout() async {
await getIt.popScope();
}This block uses Session and CartRepository from the Provider example (import them, or move them to a shared file).
Things to know about get_it scopes:
- Scopes form a stack.
popScoperemoves only the top one, so push and pop must be paired. If login can run twice, pop the old scope first or usedropScope('session'), which removes a scope by name. - The
disposeargument on a registration runs when that scope is popped. An object never registered with adisposecallback is just dropped. - Anything registered in an outer scope that was built before the push cannot see the session. If you resolve a session object inside an app-scoped singleton and store it, you have broken the rule above. Resolve scoped objects at the point of use, in scoped registrations, or in factories.
- A factory registered in the app scope can still resolve scoped objects each time it runs. For example, a view model factory can call
getIt<CartRepository>()when it is created. This is safe as long as the view model itself does not outlive the session.
Scoping with Riverpod
Riverpod ties lifetime to listeners and to the providers a value watches. Two tools cover most scoping needs, shown here for Riverpod 2.x.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final sessionProvider = StateProvider<Session?>((ref) => null);
final cartRepositoryProvider = Provider.autoDispose<CartRepository>((ref) {
final session = ref.watch(sessionProvider);
if (session == null) {
throw StateError('No signed-in user');
}
final repository = CartRepository(session);
ref.onDispose(repository.dispose);
return repository;
});
void logOut(WidgetRef ref) {
ref.read(sessionProvider.notifier).state = null;
}autoDisposeremoves the provider's state when nothing listens to it. This gives you feature scope. Leave the screen and the state is freed.- Watching
sessionProvidergives you session scope. When the session changes, Riverpod disposes the old repository, runsonDispose, and rebuilds only if something still listens. - Calling
ref.invalidate(provider)forces the same reset for one provider. After logout, invalidate every provider that holds user data. - A widget that still watches
cartRepositoryProviderat logout would see theStateError. Navigate to the login screen first, or make the provider return nullable data. - A nested
ProviderScopewithoverridescan give one subtree its own value for a provider. Declare the provider'sdependencieswhen you do this, so providers that read it know to follow the override.
Comparing the three
| Approach | How a scope starts | How a scope ends | Disposal |
|---|---|---|---|
| Provider | A provider widget enters the tree | The widget leaves the tree or its key changes | Automatic through the `dispose` callback or a `ChangeNotifier` |
| get_it | `pushNewScope` | `popScope` or `dropScope` | Registration `dispose` callbacks, run on pop |
| Riverpod | First listener, or a watched value changes | No listeners (`autoDispose`), `invalidate`, or a changed watched value | `ref.onDispose` |
Provider ties scope to the widget tree, which makes it hard to forget cleanup, but you can only inject where a BuildContext exists. get_it works anywhere in plain Dart, but you must call push and pop yourself, and a missed pop leaks the session.
Common errors
- Stale user data after logout. An app-scoped object kept a reference to a session object. Move that object into the session scope.
ProviderNotFoundExceptionin a pushed route. The provider sits in a widget that is not an ancestor of the route. Move it above theNavigatoror into the route's builder.- Scope not reset on login. A provider in the tree keeps its state when only its values change. Add a
ValueKeyon the user ID, or rebuild the scope widget. - Duplicate scopes in get_it. Calling
pushNewScopeon every login without a pop leaves old scopes in the stack. - Disposing something you did not create.
Provider.valuedoes not dispose, anddisposeon a registration runs for whatever you registered. Pair creation and disposal with the owner.
Exercise
An app registers an AnalyticsService in the app scope, and its constructor takes a Session read from the session scope so it can tag events with the user ID. After logout and a second login, events carry the first user's ID. What rule was broken, and how do you fix it?
Show answer
The rule is that a dependency must not depend on a shorter-lived scope. The long-lived AnalyticsService captured the first Session and kept it. Either move AnalyticsService into the session scope so it is rebuilt on each login, or keep it in the app scope and pass the user ID to each call (or read it from a current-session holder at call time) instead of storing the session.
Exercise
You push a checkout route with Navigator.push, and the route's builder returns a ChangeNotifierProvider<CheckoutViewModel>. When is the view model disposed, and why can the route still read CartRepository?
Show answer
ChangeNotifierProvider disposes the view model when the route is popped and its widgets leave the tree. The route can read CartRepository because the provider for it sits above the Navigator (in the session scope), and routes are descendants of the Navigator.