0
0
Fluttermobile~3 mins

Why ChangeNotifier and Consumer in Flutter? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could update itself instantly without you writing extra code every time?

The Scenario

Imagine you have a shopping list app where you manually update the screen every time you add or remove an item. You have to write code to check for changes and refresh the UI yourself.

The Problem

This manual approach is slow and error-prone. You might forget to update the UI, causing the app to show old data. It also makes your code messy and hard to maintain as your app grows.

The Solution

ChangeNotifier and Consumer work together to automatically update the UI when data changes. ChangeNotifier tells the app when something changes, and Consumer listens and rebuilds only the parts of the UI that need updating.

Before vs After
Before
setState(() {
  items.add(newItem);
});
After
class ItemList extends ChangeNotifier {
  List<String> items = [];
  void addItem(String item) {
    items.add(item);
    notifyListeners();
  }
}

Consumer<ItemList>(builder: (context, itemList, child) {
  return Text('Items: ${itemList.items.length}');
})
What It Enables

This lets your app react instantly and efficiently to data changes, making your UI always up-to-date without extra manual work.

Real Life Example

In a chat app, when a new message arrives, ChangeNotifier notifies the UI, and Consumer updates the message list automatically, so you see new messages right away.

Key Takeaways

Manual UI updates are slow and error-prone.

ChangeNotifier signals data changes clearly.

Consumer rebuilds UI parts automatically and efficiently.