Sub topic 9
Rebuilding the view with ListenableBuilder and Provider
This chapter assumes you know the view model from the previous chapter: a class that extends ChangeNotifier, exposes state through getters, and calls notifyListeners() after each change. You should also be comfortable with StatefulWidget, initState, and BuildContext. Here you connect that view model to widgets so the screen redraws when the state changes.
What a rebuild actually involves
A view model changes state, but a widget does not rebuild just because an object it reads changed. Something must subscribe to the view model, and on each notification it must ask Flutter to run build again.
ChangeNotifier implements Listenable, an interface with addListener and removeListener. ListenableBuilder is a widget that:
- Calls
addListeneron the object you pass aslistenablewhen it is inserted into the tree. - Calls
setStateinternally each time the listener fires. - Calls your
builderfunction again, which produces a new subtree. - Calls
removeListenerwhen it is removed or when thelistenableinstance changes.
The view never changes state itself. It forwards events to the view model and redraws from whatever the getters return.
Connecting with ListenableBuilder
ListenableBuilder is part of Flutter, so it needs no extra package. The screen below receives its view model through the constructor and triggers the first load in initState.
import 'package:flutter/material.dart';
class TodoScreen extends StatefulWidget {
const TodoScreen({super.key, required this.viewModel});
final TodoListViewModel viewModel;
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
@override
void initState() {
super.initState();
widget.viewModel.load();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: ListenableBuilder(
listenable: widget.viewModel,
builder: (context, _) {
final vm = widget.viewModel;
if (vm.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (vm.error != null) {
return Center(child: Text('Something went wrong: ${vm.error}'));
}
return ListView(
children: [
for (final todo in vm.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => vm.toggle(todo),
),
],
);
},
),
);
}
}Three details matter here:
- The builder checks state in a fixed order. Loading comes first, then error, then data. The view picks one branch from the current state and holds no state of its own.
load()runs ininitState, not inbuild.buildcan run many times per second.initStateruns once perStateobject. Whenload()callsnotifyListeners()there, theListenableBuilderhas not subscribed yet, so nothing is notified.onChangedcalls a view model method. The widget does not edittodo.doneor call the repository. This is the "actions flow in" half of the data flow.
Limiting what rebuilds
The builder runs in full on every notification. If part of the subtree never depends on view model state, pass it as child. Flutter builds it once and hands it back to your builder.
import 'package:flutter/material.dart';
class TodoPanel extends StatelessWidget {
const TodoPanel({super.key, required this.viewModel});
final TodoListViewModel viewModel;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: viewModel,
child: const Padding(
padding: EdgeInsets.all(16),
child: Text('Your tasks', style: TextStyle(fontSize: 20)),
),
builder: (context, child) {
final remaining = viewModel.todos.where((t) => !t.done).length;
return Column(
children: [
child!,
Text('$remaining left'),
],
);
},
);
}
}You can also wrap only the part of a screen that changes. A small ListenableBuilder near the leaves rebuilds less than one around the whole Scaffold. To listen to several view models at once, pass Listenable.merge([a, b]).
Connecting with Provider
ListenableBuilder needs the view model passed down by hand. In a deep tree, that means threading it through many constructors. The provider package (flutter pub add provider) puts the object in the widget tree so any descendant can look it up through BuildContext.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
Provider<TodoRepository>(
create: (_) => InMemoryTodoRepository(),
child: const MaterialApp(home: TodoPage()),
),
);
}
class TodoPage extends StatelessWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) =>
TodoListViewModel(repository: context.read<TodoRepository>())..load(),
child: Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: Consumer<TodoListViewModel>(
builder: (context, vm, _) {
if (vm.isLoading) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final todo in vm.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => vm.toggle(todo),
),
],
);
},
),
),
);
}
}The pieces work as follows:
Provider<TodoRepository>stores one repository for the whole app. It does not listen to anything, because the repository is not aListenable.ChangeNotifierProvidercreates the view model lazily on first access and calls itsdispose()when the provider leaves the tree. You do not writedisposeplumbing in the widget.Consumer<TodoListViewModel>looks up the view model, subscribes to it, and rebuilds itsbuilderon each notification...load()is the cascade operator. It callsload()on the new view model and still returns the view model itself.
Reading the provider from context
Consumer is one of several ways to reach the same value. The extension methods on BuildContext are shorter:
| Call | Subscribes to changes | Use it in |
|---|---|---|
| `context.watch<T>()` | Yes, rebuilds the calling widget on every notification | `build` methods |
| `context.select<T, R>((vm) => ...)` | Yes, but only when the selected value changes | `build` methods |
| `context.read<T>()` | No | Callbacks such as `onPressed`, and `create` functions |
| `Consumer<T>` | Yes, rebuilds only its builder | When you want a narrow rebuild without a new widget class |
select is the tool for narrow rebuilds. This widget redraws only when the number of unfinished todos changes, not when a title changes or isLoading flips:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class RemainingCount extends StatelessWidget {
const RemainingCount({super.key});
@override
Widget build(BuildContext context) {
final remaining = context.select<TodoListViewModel, int>(
(vm) => vm.todos.where((t) => !t.done).length,
);
return Text('$remaining left');
}
}A button that triggers an action should use read, because the button itself does not depend on the state:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ReloadButton extends StatelessWidget {
const ReloadButton({super.key});
@override
Widget build(BuildContext context) {
return IconButton(
icon: const Icon(Icons.refresh),
onPressed: () => context.read<TodoListViewModel>().load(),
);
}
}Choosing between them
Both approaches use the same view model. They differ in where the view model lives and who owns its lifetime.
| Concern | `ListenableBuilder` alone | `provider` |
|---|---|---|
| Extra dependency | None | `provider` package |
| Getting the view model to a deep widget | Constructor parameters | `context.read` or `context.watch` |
| Who creates and disposes it | You, in a `State` or at app start | `ChangeNotifierProvider` |
| Fine-grained rebuilds | Separate builders and `child` | `select` and `Consumer` |
For a screen or two, constructor passing is clear and easy to follow. When many widgets need the same view model, or when you want the provider to manage disposal, use provider.
Common errors
- Creating the view model inside
build.TodoListViewModel(...)in abuildmethod makes a new object, with empty state, each time the widget rebuilds. Create it in aStatefield, ininitState, or inChangeNotifierProvider.create. - Using
ChangeNotifierProvider.valuefor an object it should own. The.valueconstructor does not dispose the object. Use it only for an instance that something else created and will dispose. - Calling
context.watchin a callback. InsideonPressed, usecontext.read.watchoutside ofbuildthrows an assertion in debug mode. ProviderNotFoundException. Thecontextyou pass toreadorwatchmust sit below the provider. InTodoPage.build, thecontextparameter sits above theChangeNotifierProviderit creates. TheConsumerbuilder gets a newcontextbelow it, which is why that code works.- Rebuilding too much. If a whole screen flashes on every small change, check whether
context.watchsits in a high-level widget. Move the read into a small widget, or useselect.
Exercise
In TodoPanel, why is the "Your tasks" header passed as child to ListenableBuilder instead of being created inside the builder?
Show answer
The builder runs on every notifyListeners() call. A widget passed as child is built once and handed back to the builder unchanged, so Flutter does not recreate the header on each notification. It only works for subtrees that do not depend on view model state.
Exercise
Write a widget TodoCountLabel that shows the total number of todos and rebuilds only when that number changes, using provider. Then say which context method a "Clear all" button's onPressed should use to call a view model method.
Show answer
Use context.select:
class TodoCountLabel extends StatelessWidget {
const TodoCountLabel({super.key});
@override
Widget build(BuildContext context) {
final count = context.select<TodoListViewModel, int>((vm) => vm.todos.length);
return Text('$count todos');
}
}
The button should use context.read<TodoListViewModel>() because a callback runs outside build and does not need to subscribe to changes.