Sub topic 12
Scoping Dependencies to a Feature or Session
Assume you know Dart classes, BuildContext, the Flutter widget tree, Futures, and basic ChangeNotifier state management. This chapter focuses on choosing how long a dependency should live and where it should be available.
What a dependency scope means
A dependency’s scope is the part of the app that can access it. Its lifetime is how long its instance exists. These choices should match the data and behavior the dependency owns.
For example:
- An application configuration object can live for the whole app.
- A checkout repository can live only while the checkout feature is open.
- A shopping cart may live until the user signs out.
- A screen controller may live only while that screen remains in the widget tree.
A feature scope prevents unrelated parts of the app from sharing state accidentally. A session scope lets several features share state for one signed-in user.
| Scope | Typical lifetime | Example |
|---|---|---|
| App | From startup to process exit | API client |
| Session | From sign-in to sign-out | Current user and cart |
| Feature | While a feature is open | Checkout controller |
| Screen | While a route is mounted | Form view model |
Scoping with the widget tree
Provider scopes a dependency to a subtree. Place the provider above every widget that needs the dependency, but no higher than necessary.
class CheckoutRepository {
Future<void> submitOrder() async {
// Send the order to a backend.
}
}
class CheckoutViewModel extends ChangeNotifier {
CheckoutViewModel(this.repository);
final CheckoutRepository repository;
bool isSubmitting = false;
Future<void> submit() async {
isSubmitting = true;
notifyListeners();
try {
await repository.submitOrder();
} finally {
isSubmitting = false;
notifyListeners();
}
}
}
class CheckoutRoute extends StatelessWidget {
const CheckoutRoute({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider(create: (_) => CheckoutRepository()),
ChangeNotifierProvider(
create: (context) =>
CheckoutViewModel(context.read<CheckoutRepository>()),
),
],
child: const CheckoutPage(),
);
}
}When CheckoutRoute leaves the widget tree, ChangeNotifierProvider disposes the view model. Provider also disposes dependencies that it created when their provider leaves the tree. This makes a route subtree a useful feature scope.
Session scopes and sign-out
A session scope usually begins after authentication and ends at sign-out. Rebuilding a subtree is often the simplest way to remove all session state:
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.user});
final User? user;
@override
Widget build(BuildContext context) {
if (user == null) {
return const LoginPage();
}
return MultiProvider(
providers: [
Provider(create: (_) => CartRepository(userId: user!.id)),
ChangeNotifierProvider(
create: (context) =>
CartViewModel(context.read<CartRepository>()),
),
],
child: const HomePage(),
);
}
}When user becomes null, Flutter replaces HomePage and its subtree with LoginPage. Session dependencies are then disposed instead of accidentally being reused by the next user.
Scoping with service locators
get_it can create explicit scopes, but you must manage their boundaries yourself.
final getIt = GetIt.instance;
void startSession(String userId) {
getIt.pushNewScope(
scopeName: 'session',
init: (scope) {
scope.registerLazySingleton<CartRepository>(
() => CartRepository(userId: userId),
);
scope.registerFactory<CartViewModel>(
() => CartViewModel(scope<CartRepository>()),
);
},
);
}
Future<void> endSession() async {
await getIt.popScope();
}A locator scope is useful when non-widget code needs the dependency. The trade-off is that the code must always call endSession. Forgetting that step can retain user data or return stale objects.
Choosing a scope
Use the smallest scope that satisfies all consumers:
- Put app-wide, stateless services in the app scope.
- Put user-specific services in the session scope.
- Put temporary workflows in a feature scope.
- Use a screen scope for controllers tied to one route.
- Dispose or replace the scope when its owner ends.
Exercise
A cart is needed by several pages after sign-in, but must be cleared at sign-out. Which scope should own it, and what must happen at sign-out?
Show answer
The session scope should own it. The app must dispose or replace that scope before the next user signs in.