Flutter State Management
State is any data that can change while the app runs and that the UI depends on: the items in a cart, whether the user is logged in, the current tab. State management is about where that data lives and how widgets are told to rebuild when it changes. Flutter gives you a ladder of options; climb only as high as your app needs.
| Approach | Where the state lives | Good for |
|---|---|---|
setState |
Inside one StatefulWidget |
State used by one widget (a form, a toggle) |
| Lifting state up | In a common parent, passed down via constructors | A few widgets close together |
InheritedWidget |
Above a subtree, read via context |
Sharing data deep in the tree (built in) |
ChangeNotifier + provider |
In a model object | Most small and medium apps |
| Riverpod, Bloc, … | Dedicated libraries | Large apps, teams, complex flows |
Step 1: local state with setState
For state that only one widget cares about, setState is perfect and simple.
class LikeButton extends StatefulWidget {
const LikeButton({super.key});
@override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton> {
bool _liked = false;
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(_liked ? Icons.favorite : Icons.favorite_border,
color: _liked ? Colors.red : null),
onPressed: () => setState(() => _liked = !_liked),
);
}
}The problem appears when another widget — say a counter in the AppBar — also needs to know the value. Passing it through five constructors ("prop drilling") gets painful.
Step 2: InheritedWidget
An InheritedWidget sits high in the tree and lets any descendant read its data with context. When it is replaced with new data, dependants rebuild. It is the mechanism behind Theme.of(context) and MediaQuery.of(context).
class CartScope extends InheritedWidget {
const CartScope({super.key, required this.itemCount, required super.child});
final int itemCount;
static CartScope of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<CartScope>()!;
@override
bool updateShouldNotify(CartScope oldWidget) =>
itemCount != oldWidget.itemCount;
}
class CartBadge extends StatelessWidget {
const CartBadge({super.key});
@override
Widget build(BuildContext context) {
final count = CartScope.of(context).itemCount; // no constructor needed
return Badge(label: Text('$count'), child: const Icon(Icons.shopping_cart));
}
}InheritedWidget only provides data; changing it still requires a StatefulWidget above it that calls setState. That boilerplate is why most apps use a package built on top of it.
Step 3: ChangeNotifier + Provider
The provider package (add it with flutter pub add provider) combines two ideas:
- A model class extending
ChangeNotifierholds the state and callsnotifyListeners()after every change. ChangeNotifierProviderplaces the model in the tree; widgets read it withcontext.watch<T>()(rebuild on change) orcontext.read<T>()(just call a method).
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Cart extends ChangeNotifier {
final List<String> _items = [];
List<String> get items => List.unmodifiable(_items);
void add(String item) {
_items.add(item);
debugPrint('Cart now has ${_items.length} item(s)');
notifyListeners(); // tell watching widgets to rebuild
}
}
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => Cart(),
child: const MaterialApp(home: ShopScreen()),
),
);
}
class ShopScreen extends StatelessWidget {
const ShopScreen({super.key});
@override
Widget build(BuildContext context) {
final cart = context.watch<Cart>();
return Scaffold(
appBar: AppBar(title: Text('Cart: ${cart.items.length}')),
body: ListView(
children: [
for (final fruit in ['Apple', 'Banana', 'Cherry'])
ListTile(
title: Text(fruit),
trailing: IconButton(
icon: const Icon(Icons.add_shopping_cart),
onPressed: () => context.read<Cart>().add(fruit),
),
),
],
),
);
}
}Cart now has 1 item(s)
Cart now has 2 item(s)
Tip: Use
context.watchinsidebuildandcontext.readinside callbacks likeonPressed. Watching in a callback causes an error; reading inbuildmeans the widget won't update.
Which should I use?
Start with setState. When two distant widgets need the same data, move it into a ChangeNotifier with provider. Reach for Riverpod or Bloc when the app and team grow and you want stricter structure and easier testing. The concepts — a single source of truth and rebuilding on change — stay the same.
Test yourself
What must a ChangeNotifier call after changing its data?
- setState()
- notifyListeners()
- rebuild()
- dispose()
Inside an onPressed callback you should access a provider with…
- context.watch<T>()
- context.read<T>()
- T.of(context)
- setState
Which built-in Flutter class lets descendants read shared data via context?
- StatelessWidget
- InheritedWidget
- GlobalKey
- Navigator