Flutter
BlocBuilder
Listen to state and rebuild UI with BlocBuilder.
BlocBuilder
BlocBuilder listens to a Cubit or Bloc and redraws the child widget when the state changes. The builder function receives the current state and returns a widget.
BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('$state');
},
)
BlocBuilder is called again on every state change.
builder function
builder takes BuildContext and the current state parameters. You can return different widgets based on the state.
BlocBuilder<CounterCubit, int>(
builder: (context, count) {
return Text('Count: $count');
},
)
builder must be pure; it should have no side effects.
Exercise Display state with BlocBuilder
In Ekrani, display the state as Text('$state') using BlocBuilder<SayacCubit, int>. On button press, call context.read<SayacCubit>().artir(). In main, call print('ekran hazır').
Show example solution
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SayacCubit extends Cubit<int> {
SayacCubit() : super(0);
void artir() => emit(state + 1);
}
void main() {
print('ekran hazır');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider<SayacCubit>(
create: (_) => SayacCubit(),
child: MaterialApp(home: Ekrani()),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<SayacCubit, int>(
builder: (context, state) => Text('$state'),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<SayacCubit>().artir(),
child: Icon(Icons.add),
),
);
}
}
Test yourself
-
When is BlocBuilder rebuilt?
- During hot reload
- When the Cubit publishes a new state
- Only on error
- Only in initState
Show answer
When the Cubit publishes a new state — BlocBuilder calls the builder function again when the Cubit publishes a new state via emit.
-
Complete BlocBuilder's builder
BlocBuilder<SayacCubit, int>(
____: (context, state) => Text('$state'),
)
Show answer
BlocBuilder<SayacCubit, int>(
builder: (context, state) => Text('$state'),
)
-
BlocBuilder parts
- BlocBuilder
- Widget listening to Cubit and redrawing
- builder
- Function producing widget from state
- context
- BuildContext parameter
- state
- Current state value
Next lesson: Summary - Bloc basics