Sub topic 1
Why Riverpod: moving state out of the widget tree
Flutter apps get hard to maintain when state has to travel through the widget tree. This chapter shows where the pain comes from and what Riverpod changes. It also explains how Riverpod's idea of state "outside the tree" works. The later chapters build on this model.
Prerequisites
This chapter assumes you already know the following:
- Dart basics: classes, generics, futures, and
async/await. - Flutter basics:
StatelessWidget,StatefulWidget, and howbuildworks. setState, and the idea of lifting state up to a common ancestor.
You need a Flutter project to run the examples. Add the package with flutter pub add flutter_riverpod.
State that lives in the widget tree
Flutter's built-in tools tie state to widgets. setState stores values in a State object, and that object lives exactly as long as its widget is in the tree. This works well for local, short-lived state such as a text field's focus or an animation's progress.
Trouble starts when two distant widgets need the same value. The usual answer is to lift the state to their nearest common ancestor and pass it down. Here is a small shop screen where the app bar shows the cart count and a button deep in the tree adds items:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ShopPage()));
class ShopPage extends StatefulWidget {
const ShopPage({super.key});
@override
State<ShopPage> createState() => _ShopPageState();
}
class _ShopPageState extends State<ShopPage> {
int _cartCount = 0;
void _addItem() => setState(() => _cartCount++);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Cart: $_cartCount')),
body: ProductList(onAdd: _addItem),
);
}
}
class ProductList extends StatelessWidget {
const ProductList({super.key, required this.onAdd});
final VoidCallback onAdd;
@override
Widget build(BuildContext context) {
return Center(child: ProductCard(onAdd: onAdd));
}
}
class ProductCard extends StatelessWidget {
const ProductCard({super.key, required this.onAdd});
final VoidCallback onAdd;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onAdd,
child: const Text('Add to cart'),
);
}
}This is correct, and it is fine for a screen this size. As the app grows, three problems appear.
- Prop drilling.
ProductListnever usesonAdd. It only forwards it. Every widget between the owner and the consumer must accept and pass along the parameter, and each new shared value adds more constructor arguments. - Coarse rebuilds.
setStaterebuildsShopPageand everything under it that is notconstor otherwise cached. Only the app bar title needed to change. - Lifetime tied to the tree. If the user leaves
ShopPage, itsStateis disposed and the cart is lost. To keep the cart you must lift the state higher, which makes the first two problems worse.
What InheritedWidget solved, and what it did not
Flutter has a built-in answer to prop drilling: InheritedWidget. A descendant can look up an ancestor with context and subscribe to it, with no constructor chain in between. Older packages such as provider build on this idea.
Looking up state through BuildContext has costs of its own:
- A lookup fails at runtime, not compile time, if no matching ancestor exists. The familiar
ProviderNotFoundExceptioncomes from this. - The state can only be read where a
BuildContextbelow the ancestor is available. Code that has no widget, such as a repository or a test, cannot reach it. - Combining two pieces of state means writing glue code inside widgets or inside a special proxy object.
- Reading a value asynchronously, and handling its loading and error states, is left to you.
Riverpod keeps the useful idea of declaring dependencies and removes the dependency on the tree's shape.
The Riverpod model: providers as global declarations
In Riverpod you describe a piece of state as a provider. A provider is an object that knows how to create a value and how to expose it. You declare it once, usually as a top-level final variable:
final cartCountProvider = NotifierProvider<CartCount, int>(CartCount.new);That variable does not hold the state. It is a recipe, a key that identifies the state. The actual value lives in a provider container, an object that stores the state of every provider that has been read. In a Flutter app, a ProviderScope widget at the root creates and owns that container.
This split has consequences:
- Because the provider is a plain global constant, any code can name it. Widgets, other providers, and tests all use the same key.
- Because the state lives in the container, it is not destroyed when a widget leaves the tree. Its lifetime is decided by the provider (the later chapter on
autoDisposecovers this). - Because lookup goes through the key and not through
BuildContext, there is no ancestor search and no "provider not found" at runtime. A missingProviderScopeis a different, easy-to-spot error.
The global variable does not create global mutable state. Two containers (for example, one per test) hold independent values for the same provider.
The same screen with Riverpod
Here is the shop screen rewritten. Do not worry about every detail yet. The Notifier class and the ref object each get their own chapter. Focus on what disappeared.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CartCount extends Notifier<int> {
@override
int build() => 0;
void add() => state++;
}
final cartCountProvider = NotifierProvider<CartCount, int>(CartCount.new);
void main() {
runApp(const ProviderScope(child: MaterialApp(home: ShopPage())));
}
class ShopPage extends StatelessWidget {
const ShopPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const CartTitle()),
body: const Center(child: AddButton()),
);
}
}
class CartTitle extends ConsumerWidget {
const CartTitle({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(cartCountProvider);
return Text('Cart: $count');
}
}
class AddButton extends ConsumerWidget {
const AddButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return ElevatedButton(
onPressed: () => ref.read(cartCountProvider.notifier).add(),
child: const Text('Add to cart'),
);
}
}Compare this with the first version:
ShopPageis now aStatelessWidgetwith no fields, andProductListis gone. Nothing needs to forward a callback.- Only
CartTitlewatches the count, so onlyCartTitlerebuilds when it changes.ShopPageandAddButtondo not rebuild. - The logic for changing the count lives in
CartCount, a plain Dart class. You can test it without pumping a widget. - The cart count survives navigation, because the container owns it, not a
Stateobject.
Trade-offs
Riverpod is not free. You take on a dependency, a small vocabulary (provider, container, ref, notifier), and a rule that every consumer widget uses ConsumerWidget or Consumer. For state that only one widget uses, setState or a StatefulWidget is still the simpler tool. The table shows where each approach fits.
| Situation | Better fit |
|---|---|
| A toggle or text controller used by one widget | `StatefulWidget` and `setState` |
| A value shared by a few widgets on one screen | Either; lifting state is fine if it stays shallow |
| State shared across screens or surviving navigation | Riverpod provider |
| Async data with loading and error states | Riverpod `AsyncValue` providers |
| Logic that must run in unit tests without widgets | Riverpod with `ProviderContainer` |
What comes next
The next chapters follow the order of the concept graph. You will meet ProviderScope and the container in detail, then read-only providers, then ConsumerWidget and ref.watch versus ref.read. Notifiers, derived providers, and async state come after that. Keep the shop example in mind, because each later idea answers one of the three problems listed above: prop drilling, coarse rebuilds, and tree-bound lifetime.
Exercise
In the Riverpod shop example, ShopPage is a StatelessWidget that never rebuilds when the cart count changes. Which widget rebuilds, why, and where is the count stored while the app runs?
Show answer
CartTitle rebuilds, because it calls ref.watch(cartCountProvider) and so subscribes to changes in that provider's state. AddButton only uses ref.read inside a callback, so it does not subscribe and does not rebuild. The count is stored in the provider container created by ProviderScope, not in any widget. cartCountProvider is only the key used to find that state.
Exercise
Name two problems with the setState version of the shop screen that the Riverpod version removes, and one situation where you would still prefer setState.
Show answer
First, prop drilling: ProductList had to accept and forward onAdd even though it never used it. Second, coarse rebuilds or tree-bound lifetime: setState rebuilds the whole ShopPage subtree, and the cart is lost when ShopPage is disposed. You would still prefer setState for purely local state, such as a toggle used by a single widget, where a provider adds vocabulary without adding benefit.