Flutter
Bloc class
Manage event -> state flow with the Bloc class.
What is a Bloc class?
A Bloc is a class that transforms events into states. Unlike Cubit, it works with event objects instead of method calls. For each event type you register a handler with on<Event>; the handler produces a new state with emit.
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0)) {
on<IncrementEvent>((event, emit) =>
emit(CounterState(state.count + 1)));
}
}
on<Event> and emit
You register a handler for an event type with on<Event>. The handler takes two parameters: the event and emit. Calling emit(newState) updates the state and notifies listening widgets. emit can only be called inside a handler.
on<IncrementEvent>((event, emit) =>
emit(CounterState(state.count + 1)));
Exercise Write a CounterBloc class
Write a class named CounterBloc that extends Bloc<CounterEvent, CounterState>. The initial value should be 0. The IncrementEvent handler should increase the counter by 1. In main, create an instance, add the event twice, wait, and print state.count.
Show example solution
import 'package:bloc/bloc.dart';
class CounterEvent {}
class IncrementEvent extends CounterEvent {}
class CounterState {
final int count;
CounterState(this.count);
}
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0)) {
on<IncrementEvent>((event, emit) =>
emit(CounterState(state.count + 1)));
}
}
void main() async {
final bloc = CounterBloc();
bloc.add(IncrementEvent());
bloc.add(IncrementEvent());
await Future.delayed(Duration(milliseconds: 10));
print(bloc.state.count);
}
Test yourself
-
What is the main difference between Bloc and Cubit?
- Bloc works with event objects, Cubit with method calls
- Bloc holds only async state, Cubit holds sync state
- Cubit uses events but Bloc does not hold state
- They are identical, only the name differs
Show answer
Bloc works with event objects, Cubit with method calls — Bloc takes event objects and produces state; in Cubit you call methods directly and emit from inside them.
-
emit call
on<IncrementEvent>((event, emit) => ____(CounterState(state.count + 1)));
Show answer
on<IncrementEvent>((event, emit) => emit(CounterState(state.count + 1)));
-
Bloc parts
- on<IncrementEvent>
- Event handler registration
- emit
- Produces state
- Bloc<Event, State>
- Two generic parameters
- super(CounterState(0))
- Initial state
Next lesson: Event classes