Sub topic 5
Rebuilding the UI with BlocBuilder, buildWhen and BlocSelector
This chapter explains how a Cubit's state changes become widget rebuilds, and how to limit rebuilds to the widgets that need them. It assumes you can read Dart 3, know StatelessWidget and BuildContext, and have a Cubit with an Equatable state. It also assumes you have used BlocProvider to make that Cubit available to a subtree.
What BlocBuilder does
BlocBuilder<B, S> is a widget that does three things:
- It finds a Cubit or Bloc of type
Babove it in the tree, the same lookupcontext.readuses. - It subscribes to that object's state stream.
- It calls your
builderfunction with the current state each time the widget needs to rebuild.
The first call happens when the widget is inserted, using the Cubit's current state. After that, each new state is passed through buildWhen. If buildWhen returns true or is omitted, the widget rebuilds.
The example model
The examples use a small todo list. Save this as lib/todos_cubit.dart. The state has two fields that change independently: the list and a saving flag.
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosState extends Equatable {
const TodosState({this.todos = const [], this.isSaving = false});
final List<String> todos;
final bool isSaving;
TodosState copyWith({List<String>? todos, bool? isSaving}) {
return TodosState(
todos: todos ?? this.todos,
isSaving: isSaving ?? this.isSaving,
);
}
@override
List<Object?> get props => [todos, isSaving];
}
class TodosCubit extends Cubit<TodosState> {
TodosCubit() : super(const TodosState());
Future<void> add() async {
emit(state.copyWith(isSaving: true));
await Future<void>.delayed(const Duration(milliseconds: 500));
if (isClosed) return;
emit(
state.copyWith(
todos: [...state.todos, 'Task ${state.todos.length + 1}'],
isSaving: false,
),
);
}
}One call to add emits two states. The first changes only isSaving. The second changes both fields. Every widget that listens to the whole state sees both emissions.
Filtering rebuilds with buildWhen
buildWhen receives the previous and current state and returns a bool. Use it when a widget depends on only part of the state.
BlocBuilder<TodosCubit, TodosState>(
buildWhen: (previous, current) => previous.todos != current.todos,
builder: (context, state) {
debugPrint('list rebuilt');
return ListView(
children: [for (final t in state.todos) ListTile(title: Text(t))],
);
},
)The list does not rebuild when only isSaving changes. This works because copyWith reuses the same list instance when no new list is passed. The != on two List values compares identity, not contents, so it reports a change only when add creates a new list.
Selecting a value with BlocSelector
BlocSelector<B, S, T> is BlocBuilder with the filter built in. You give it a selector that extracts a value of type T from the state. The builder runs only when the selected value changes under ==, and it receives the selected value instead of the whole state.
BlocSelector<TodosCubit, TodosState, int>(
selector: (state) => state.todos.length,
builder: (context, count) => Text('Todos ($count)'),
)Select values that compare well with ==: numbers, strings, booleans, enums, and Equatable objects. A selector that returns a freshly built collection never matches the previous one, so it rebuilds on every state.
// Rebuilds on every emission: toList() creates a new list each time.
selector: (state) => state.todos.where((t) => t.startsWith('Task')).toList(),Select a primitive such as a count, or do the filtering inside the builder.
| Tool | Receives in builder | Rebuild rule | Best for |
|---|---|---|---|
| `BlocBuilder` | Whole state | Every state that differs from the last | Widgets that read most of the state |
| `BlocBuilder` with `buildWhen` | Whole state | Only when `buildWhen` returns `true` | A custom rule over previous and current state |
| `BlocSelector` | One selected value | Only when the value changes | Widgets that read one field or a derived primitive |
| `context.select` | One selected value, inside `build` | Only when the value changes | Same goal, but you read it in an existing `build` method |
Putting it together
Save this as lib/main.dart. Each widget watches only what it draws.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'todos_cubit.dart';
void main() => runApp(const MaterialApp(home: TodosPage()));
class TodosPage extends StatelessWidget {
const TodosPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => TodosCubit(),
child: const TodosView(),
);
}
}
class TodosView extends StatelessWidget {
const TodosView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: BlocSelector<TodosCubit, TodosState, int>(
selector: (state) => state.todos.length,
builder: (context, count) {
debugPrint('title rebuilt');
return Text('Todos ($count)');
},
),
),
body: BlocBuilder<TodosCubit, TodosState>(
buildWhen: (previous, current) => previous.todos != current.todos,
builder: (context, state) {
debugPrint('list rebuilt');
return ListView(
children: [for (final t in state.todos) ListTile(title: Text(t))],
);
},
),
floatingActionButton: BlocSelector<TodosCubit, TodosState, bool>(
selector: (state) => state.isSaving,
builder: (context, isSaving) => FloatingActionButton(
onPressed: isSaving ? null : () => context.read<TodosCubit>().add(),
child: Icon(isSaving ? Icons.hourglass_empty : Icons.add),
),
),
);
}
}Tap the button once and read the console. The button rebuilds twice, once when saving starts and once when it ends. The title and list rebuild once each, after the save completes.
Common mistakes
- Putting side effects in the builder. Flutter can call a builder many times, and it must return a widget without other effects. Do not navigate or show a SnackBar there. Use
BlocListener, covered in the next chapter. - Wrapping the whole screen. A
BlocBuilderaround aScaffoldrebuilds everything beneath it. Put the builder as low in the tree as you can. - Mutating the list in place. Mutation changes the old state's data as well, so the new state equals the old one and Bloc drops the emission.
void addBroken(String title) {
state.todos.add(title); // changes the list the current state already holds
emit(state.copyWith()); // equal to the current state, so nothing is emitted
}With the const [] default, add throws an UnsupportedError. With a growable list, the UI silently stays stale. The fix is to create a new list.
void addFixed(String title) {
emit(state.copyWith(todos: [...state.todos, title]));
}- Using Equatable's deep equality in
buildWhenby accident. Comparing whole states with==usesprops, which compares list contents. Comparing two fields with!=compares identity for plain lists. Know which one you are writing.
Exercise
In the final example, the user taps the button once. List the rebuilds of the title, the list, and the button, and say which mechanism prevents the others.
Show answer
The Cubit emits two states. In the first, only isSaving changes, so the button rebuilds (selector value changed from false to true). The title selector value is unchanged and the list's buildWhen sees the same list instance, so both skip. In the second state, todos gets a new list and isSaving returns to false. The title rebuilds because the length changed, the list rebuilds because previous.todos != current.todos, and the button rebuilds because its value changed back. In total, the button rebuilds twice and the title and list once each.
Exercise
A teammate writes BlocSelector<TodosCubit, TodosState, List<String>>(selector: (s) => List.of(s.todos), ...) to "copy the list safely". The widget now rebuilds when only isSaving changes. Why, and what is a better selector?
Show answer
List.of creates a new list on every call, and List equality is by identity, so the selected value never equals the previous one and the builder runs on every emission. Select s.todos directly, which keeps the same instance when copyWith does not replace it. If the widget needs only a derived primitive, select that instead, for example s.todos.length.