ChangeNotifier helps your app know when data changes. Consumer listens and updates the screen automatically.
0
0
ChangeNotifier and Consumer in Flutter
Introduction
When you want to update the screen after data changes without rebuilding everything.
When you have a shared data model used by many parts of your app.
When you want to keep your UI and data separate and clean.
When you want to avoid manual setState calls for better performance.
Syntax
Flutter
class MyModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } Consumer<MyModel>( builder: (context, myModel, child) { return Text('Count: ${myModel.count}'); }, )
ChangeNotifier is a class you extend to create data models that can notify listeners.
Consumer is a widget that listens to a ChangeNotifier and rebuilds when notified.
Examples
This creates a simple counter model that notifies when the value changes.
Flutter
class Counter extends ChangeNotifier { int value = 0; void increment() { value++; notifyListeners(); } }
This widget listens to the Counter model and shows the current value.
Flutter
Consumer<Counter>(
builder: (context, counter, child) {
return Text('Value: ${counter.value}');
},
)This example shows how to provide the model and use Consumer to update UI on button press.
Flutter
Provider(
create: (_) => Counter(),
child: Consumer<Counter>(
builder: (context, counter, child) {
return ElevatedButton(
onPressed: counter.increment,
child: Text('Increment'),
);
},
),
)Sample App
This app shows a number on screen. Pressing the + button increases the number. The screen updates automatically because Consumer listens to the Counter model.
Flutter
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class Counter extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } void main() { runApp( ChangeNotifierProvider( create: (_) => Counter(), child: const MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('ChangeNotifier & Consumer')), body: Center( child: Consumer<Counter>( builder: (context, counter, child) { return Text('Count: ${counter.count}', style: const TextStyle(fontSize: 30)); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () => context.read<Counter>().increment(), child: const Icon(Icons.add), ), ), ); } }
OutputSuccess
Important Notes
Always call notifyListeners() after changing data to update UI.
Use ChangeNotifierProvider to make your model available to widgets.
Consumer rebuilds only the widgets that need updating, improving performance.
Summary
ChangeNotifier holds data and tells listeners when data changes.
Consumer listens to ChangeNotifier and rebuilds UI automatically.
This pattern helps keep UI and data separate and responsive.