Sub topic 5
Rebuilding the UI with BlocBuilder, buildWhen and BlocSelector
This chapter assumes Dart classes, generics, null safety, and async code. It also assumes that you know Flutter widgets, BuildContext, and basic Bloc or Cubit usage.
A Cubit emits a new state when something changes. Flutter widgets can listen to those states and rebuild themselves. BlocBuilder is the usual tool for this job:
BlocBuilder<CounterCubit, CounterState>(
builder: (context, state) {
return Text('${state.count}');
},
)The builder function runs when the Cubit emits a state. The widget returned by the function replaces the previous widget.
Limit rebuilds with `buildWhen`
A state can contain several values. Not every widget needs every value. Use buildWhen when a widget should rebuild only for a particular change.
BlocBuilder<CounterCubit, CounterState>(
buildWhen: (previous, current) =>
previous.count != current.count,
builder: (context, state) {
return Text('${state.count}');
},
)buildWhen receives the previous and current states. Return true to rebuild and false to skip the rebuild.
Use this filter for performance or for clearer intent. Do not use it to hide incorrect state changes. The state must still contain the complete truth of the feature.
Select one value with `BlocSelector`
BlocSelector listens to a state and converts it into one smaller value. The widget rebuilds only when that selected value changes.
BlocSelector<CounterCubit, CounterState, int>(
selector: (state) => state.count,
builder: (context, count) {
return Text('$count');
},
)The selected value should be immutable. If the selector returns a mutable list and that list changes in place, Bloc may not detect the change correctly. Create a new list when updating state.
| Tool | Listens to | Rebuild condition |
|---|---|---|
| `BlocBuilder` | The complete state | Every emitted state |
| `BlocBuilder` with `buildWhen` | The complete state | Your predicate returns `true` |
| `BlocSelector` | A selected value | The selected value changes |
A complete example
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterState extends Equatable {
const CounterState({this.count = 0, this.message = ''});
final int count;
final String message;
CounterState copyWith({int? count, String? message}) {
return CounterState(
count: count ?? this.count,
message: message ?? this.message,
);
}
@override
List<Object> get props => [count, message];
}
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(const CounterState());
void increment() {
emit(state.copyWith(count: state.count + 1));
}
void setMessage(String message) {
emit(state.copyWith(message: message));
}
}
class CounterPage extends StatelessWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
BlocSelector<CounterCubit, CounterState, int>(
selector: (state) => state.count,
builder: (context, count) => Text('Count: $count'),
),
BlocBuilder<CounterCubit, CounterState>(
buildWhen: (previous, current) =>
previous.message != current.message,
builder: (context, state) => Text(state.message),
),
ElevatedButton(
onPressed: () =>
context.read<CounterCubit>().setMessage('Updated'),
child: const Text('Update message'),
),
ElevatedButton(
onPressed: () => context.read<CounterCubit>().increment(),
child: const Text('Increment'),
),
],
),
),
);
}
}
void main() {
runApp(const MaterialApp(home: CounterPage()));
}The count text rebuilds only when count changes. The message text rebuilds only when message changes.
Exercise
Which tool should display a user's name but rebuild only when the name changes: BlocBuilder without a filter, buildWhen, or BlocSelector?
Show answer
Use BlocSelector and select the name from the state. The selected name is compared with its previous value.