Sub topic 6
Keeping State Inside the Feature
This chapter assumes you can build Flutter screens with widgets and navigation. It also assumes you know the export directive, have used one state management approach (ChangeNotifier, Riverpod, or Bloc), and understand the repository pattern. The examples use ChangeNotifier and ListenableBuilder, which ship with Flutter. The placement rules apply the same way to other libraries.
What feature-scoped state means
In a feature-first project, the state that drives a feature's screens lives in that feature's presentation folder. It does not sit in a top-level providers/ or blocs/ folder. A feature's state object:
- Reads data only through the feature's domain interfaces, such as
CartRepository. - Is created when the feature is needed and disposed when it is no longer needed.
- Is not imported by any other feature.
The last rule matters most. If the checkout feature imports CartController, checkout now depends on the cart's internals. Changing how the cart loads data can then break checkout. The earlier chapters on dependency rules and public APIs already forbid this kind of import, and state objects are the most common place where the rule gets broken.
Three kinds of state and where each lives
Not all state belongs in a controller. Putting everything in one place is as harmful as putting everything in global scope.
| Kind of state | Example | Where it lives |
|---|---|---|
| Ephemeral UI state | Whether a text field is focused, a tab index | A `StatefulWidget` inside the feature |
| Feature state | The cart's items, loading and error status | A controller in `features/cart/presentation/` |
| App-wide state | Signed-in user, theme mode, locale | `core/` or `app/`, exposed through a small interface |
| State another feature needs | Number of items in the cart | A contract in `core/contracts/`, implemented by the owning feature |
Ask two questions to place a piece of state. Who reads it? Who is allowed to change it? If only one feature reads and changes it, keep it in that feature. If several features read it, the owner keeps the writes, and readers see only a read-only contract.
Modeling the state
Give the feature one explicit state type. A sealed class makes the screen handle every case, and the compiler reports a missing one.
// lib/features/cart/domain/cart_item.dart
class CartItem {
const CartItem({
required this.id,
required this.name,
required this.priceCents,
});
final String id;
final String name;
final int priceCents;
}// lib/features/cart/presentation/cart_state.dart
import '../domain/cart_item.dart';
sealed class CartState {
const CartState();
}
class CartLoading extends CartState {
const CartLoading();
}
class CartLoaded extends CartState {
const CartLoaded(this.items);
final List<CartItem> items;
}
class CartFailed extends CartState {
const CartFailed(this.message);
final String message;
}The state type sits in presentation/ because it describes what the screen shows. The domain layer has no loading or failed concept. It only knows items and repositories.
The controller
The controller depends on the domain interface, never on InMemoryCartRepository or any other data-layer class. That keeps the dependency pointing inward, as in the repository example from earlier in this tutorial.
// lib/features/cart/presentation/cart_controller.dart
import 'package:flutter/foundation.dart';
import '../domain/cart_item.dart';
import '../domain/cart_repository.dart';
import 'cart_state.dart';
class CartController extends ChangeNotifier {
CartController(this._repository);
final CartRepository _repository;
CartState _state = const CartLoading();
bool _disposed = false;
CartState get state => _state;
Future<void> load() async {
_emit(const CartLoading());
await _read();
}
Future<void> add(CartItem item) async {
try {
await _repository.addItem(item);
} catch (_) {
_emit(const CartFailed('Could not add the item.'));
return;
}
await _read();
}
Future<void> _read() async {
try {
_emit(CartLoaded(await _repository.loadItems()));
} catch (_) {
_emit(const CartFailed('Could not load the cart.'));
}
}
void _emit(CartState next) {
if (_disposed) return;
_state = next;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}The _disposed guard handles an edge case. A repository call can finish after the user has left the screen and the controller was disposed. Calling notifyListeners on a disposed ChangeNotifier throws in debug builds. Guarding the single _emit method fixes this once for every code path.
Owning the lifetime in the page
The page creates the controller and disposes it. The controller therefore lives exactly as long as the screen that uses it.
// lib/features/cart/presentation/cart_page.dart
import 'package:flutter/material.dart';
import '../domain/cart_repository.dart';
import 'cart_controller.dart';
import 'cart_state.dart';
class CartPage extends StatefulWidget {
const CartPage({super.key, required this.repository});
final CartRepository repository;
@override
State<CartPage> createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
late final CartController _controller =
CartController(widget.repository)..load();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Cart')),
body: ListenableBuilder(
listenable: _controller,
builder: (context, _) {
return switch (_controller.state) {
CartLoading() =>
const Center(child: CircularProgressIndicator()),
CartFailed(:final message) => Center(child: Text(message)),
CartLoaded(:final items) => ListView(
children: [
for (final item in items)
ListTile(
title: Text(item.name),
trailing: Text('${item.priceCents / 100}'),
),
],
),
};
},
),
);
}
}The route example earlier in this tutorial wrote const CartPage() with no arguments. Here the page takes a repository because the feature must not construct its own data-layer class. Where that repository comes from is decided by the app shell. The chapter on wiring features together covers that step. Until then, the route builder can pass InMemoryCartRepository() directly.
How the pieces depend on each other
Presentation depends on domain, and data implements domain. The only line that crosses the feature boundary goes through CartSummary, which belongs to shared code.
Common errors
- Global provider folders. A top-level
lib/providers/directory recreates layer-first organization for state. A reader must jump between two trees to understand one feature. - Exporting the controller from the barrel file. Once
cart.dartexportsCartController, every feature can import and depend on it. Export only what other features need, which is usually a contract, a route list, or a domain type. - Reading another feature's controller. Checkout calling
CartController.statecouples the two features. Use aCartSummary-style interface incore/contracts/instead. - Long-lived controllers for short-lived screens. A controller created in
main()keeps stale data and never releases resources. Create it where the feature starts, and dispose it where the feature ends. - Business rules in the controller. Rules such as "a cart holds at most 20 items" belong in the domain layer. A controller should translate between domain results and screen state, and nothing more.
Testing the controller
A controller that depends on an interface can be tested with a hand-written fake. No widgets, network, or storage are involved. The test file mirrors the feature path, as the test layout chapter describes.
// test/features/cart/presentation/cart_controller_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/features/cart/domain/cart_item.dart';
import 'package:my_app/features/cart/domain/cart_repository.dart';
import 'package:my_app/features/cart/presentation/cart_controller.dart';
import 'package:my_app/features/cart/presentation/cart_state.dart';
class FakeCartRepository implements CartRepository {
FakeCartRepository({this.shouldFail = false});
final bool shouldFail;
final List<CartItem> _items = [];
@override
Future<List<CartItem>> loadItems() async {
if (shouldFail) throw Exception('offline');
return List.unmodifiable(_items);
}
@override
Future<void> addItem(CartItem item) async => _items.add(item);
}
void main() {
const apple = CartItem(id: '1', name: 'Apple', priceCents: 120);
test('add then load exposes the item', () async {
final controller = CartController(FakeCartRepository());
await controller.load();
await controller.add(apple);
final state = controller.state;
expect(state, isA<CartLoaded>());
expect((state as CartLoaded).items.single.name, 'Apple');
});
test('a failing repository produces CartFailed', () async {
final controller = CartController(FakeCartRepository(shouldFail: true));
await controller.load();
expect(controller.state, isA<CartFailed>());
});
}Replace my_app with the package name from your pubspec.yaml.
Using another state library
The placement rules do not change with the library:
- A Riverpod
Notifierand its provider go infeatures/cart/presentation/and are not exported from the barrel file. - A Bloc, its events, and its states go in the same folder.
- If you use Riverpod, the provider that exposes the repository interface can be overridden in the app shell. This is the library's version of passing a repository into the page.
Exercise
A checkout screen needs to show the number of items in the cart. Which of these is the correct design: (a) checkout imports CartController, (b) checkout imports a CartSummary interface from core/contracts/ that the app shell backs with the cart feature, or (c) the cart items are moved into a global lib/providers/ folder? Give one reason for your choice.
Show answer
Option (b). Checkout depends only on a small read-only contract in shared code, so it does not know how the cart loads or stores data, and the cart's internals can change without touching checkout. Option (a) couples checkout to the cart's internals, and option (c) recreates a layer-first folder for state.
Exercise
A user opens the cart page and leaves before loadItems completes. The controller has been disposed when the future finishes. What error can occur in the controller above, and which part of the code prevents it?
Show answer
Calling notifyListeners on a disposed ChangeNotifier throws an error in debug builds. The disposed flag, set in dispose() and checked at the start of emit(), makes late results get ignored, because every state change goes through _emit().