
Flutter Change Notifier
Use when setting up ChangeNotifier models, providing them to the widget tree, consuming...
Install
npx skills add evanca/flutter-ai-rules --skill flutter-change-notifier -g -a claude-code -y- Repository
- evanca/flutter-ai-rules668
- Category
- Engineering
- Updated
- 5d ago
- License
- MIT
- Context cost
- Lightabout 776 tokens
- Runs scripts
- No, instructions only
What it does
Use when setting up ChangeNotifier models, providing them to the widget tree, consuming state with Consumer or Provider.of, or optimizing rebuilds.
Flutter ChangeNotifier Skill
This skill defines how to correctly use ChangeNotifier with the provider package for state management in Flutter.
1. Model
Extend ChangeNotifier to manage state. Keep internal state private and expose unmodifiable views. Call notifyListeners() on every state change.
class CartModel extends ChangeNotifier {
final List<Item> _items = [];
UnmodifiableListView<Item> get items => UnmodifiableListView(_items);
void add(Item item) {
_items.add(item);
notifyListeners();
}
void removeAll() {
_items.clear();
notifyListeners();
}
}
- Place shared state above the widgets that use it in the widget tree.
- Never directly mutate widgets or call methods on them to change state, rebuild widgets with new data instead.
2. Providing the Model
ChangeNotifierProvider(
create: (context) => CartModel(),
child: MyApp(),
)
ChangeNotifierProviderautomatically disposes of the model when it is no longer needed.- Use
MultiProviderwhen you need to provide multiple models:
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => CartModel()),
ChangeNotifierProvider(create: (_) => UserModel()),
],
child: MyApp(),
)
3. Consuming State
Consumer
Consumer<CartModel>(
builder: (context, cart, child) => Stack(
children: [
if (child != null) child,
Text('Total price: ${cart.totalPrice}'),
],
),
child: const SomeExpensiveWidget(), // rebuilt only once
)
- Always specify the generic type (
Consumer<CartModel>, notConsumer). - Use the
childparameter to pass widgets that don't depend on the model, they are built once and reused. - Place
Consumerwidgets as deep in the widget tree as possible to minimize the scope of rebuilds:
