Step 1 / 4
A model that can notify
ChangeNotifier is a built-in Flutter class. Your model keeps its data private and exposes methods that change it.
Expose a ChangeNotifier to the widget tree and rebuild only the widgets that listen to it.
1class CartModel extends ChangeNotifier {2 final _items = <Item>[];3 List<Item> get items => List.unmodifiable(_items);45 void add(Item item) {6 _items.add(item);7 notifyListeners();8 }9}1011void main() => runApp(12 ChangeNotifierProvider(13 create: (_) => CartModel(),14 child: const MyApp(),15 ),16);1718// Inside any widget below:19final count = context.watch<CartModel>().items.length;20context.read<CartModel>().add(item);
items: 0build ×1watchbuild ×1readbuild ×1readbuild ×1readbuild ×1watchbuild ×1Only widgets that watch Cart rebuild. Tiles use read: they call add() but never rebuild.
ChangeNotifier is a built-in Flutter class. Your model keeps its data private and exposes methods that change it.