Sub topic 9
Rebuilding the View with ListenableBuilder and Provider
This chapter assumes you know Dart classes, async and await, Flutter widget lifecycle methods, and ChangeNotifier. It also assumes you have a view model with readable state and methods such as load() and toggle().
A view model does not rebuild widgets by itself. It announces that its state changed. A widget must listen to those announcements and rebuild the part of the interface that depends on the state.
Connecting a view with ListenableBuilder
ListenableBuilder is a Flutter widget that rebuilds its builder function when a Listenable changes. ChangeNotifier implements Listenable, so a view model can be passed directly to it.
import 'package:flutter/material.dart';
class CounterViewModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key, required this.viewModel});
final CounterViewModel viewModel;
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
@override
void dispose() {
widget.viewModel.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: ListenableBuilder(
listenable: widget.viewModel,
builder: (context, child) {
return Center(
child: Text('Count: ${widget.viewModel.count}'),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: widget.viewModel.increment,
child: const Icon(Icons.add),
),
);
}
}
void main() {
final viewModel = CounterViewModel();
runApp(
MaterialApp(
home: CounterPage(viewModel: viewModel),
),
);
}The widget reads the view model's current state during build. The button sends an action to the view model. The view model changes its state and calls notifyListeners(). Flutter then runs the builder again.
Keep the listening area as small as practical. If only a list depends on the view model, place ListenableBuilder around the list instead of the entire screen. The child parameter can hold a widget that does not depend on the state, avoiding unnecessary rebuilds.
Using Provider to supply and listen
provider is a package that places objects in the widget tree and retrieves them below that location. Add provider to pubspec.yaml, then create the view model with ChangeNotifierProvider.
ChangeNotifierProvider(
create: (context) => TodoListViewModel(
repository: context.read<TodoRepository>(),
)..load(),
child: Scaffold(
body: Consumer<TodoListViewModel>(
builder: (context, viewModel, child) {
if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (viewModel.error != null) {
return Center(child: Text('Could not load todos'));
}
return ListView(
children: [
for (final todo in viewModel.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => viewModel.toggle(todo),
),
],
);
},
),
),
)Consumer listens to the nearest matching provider and supplies the current view model to its builder. Use context.read<T>() when you need an object without rebuilding for its changes. Use context.watch<T>() when the surrounding build method should rebuild.
ChangeNotifierProvider also disposes the view model that it creates. Do not manually call dispose on that instance. Choose one owner for each view model.
Exercise
Why does a view model need to call notifyListeners after changing state?
Show answer
ListenableBuilder and Consumer rebuild only after receiving a notification. Changing a private field alone does not tell Flutter that the displayed state is stale.