What is Bloc?
- Flutter course
- Intermediate
- Lesson 16/99
- 4 min
Learn how Bloc manages an event -> state flow.
What is Bloc?
Bloc (Business Logic Component) is a state management library that transforms incoming events into new states. Events are sent to the Bloc, the Bloc processes them and emits the resulting state. This unidirectional flow makes state changes predictable.
event -> Bloc -> stateBloc separates business logic from the UI.
Event and State flow
A Bloc listens to events with on<Event> and produces new state with emit. The state is published as a Stream; listening widgets update on every new state.
on<Increment>((event, emit) {
emit(CounterState(state.value + 1));
});This flow is testable and observable.
Practice Define the SayacBloc class
Make SayacBloc extend Bloc<SayacEvent, SayacState>. Listen to the event with on<Artir> and produce a new state with emit. In main, call print('bloc hazır').
Starter code
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class SayacEvent {}
class Artir extends SayacEvent {}
class SayacState {
final int deger;
SayacState(this.deger);
}
// SayacBloc, Bloc<SayacEvent, SayacState>'ten türetilsin
void main() {
print('bloc hazır');
}Sample solution
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class SayacEvent {}
class Artir extends SayacEvent {}
class SayacState {
final int deger;
SayacState(this.deger);
}
class SayacBloc extends Bloc<SayacEvent, SayacState> {
SayacBloc() : super(SayacState(0)) {
on<Artir>((event, emit) {
emit(SayacState(state.deger + 1));
});
}
}
void main() {
print('bloc hazır');
}Expected output
bloc hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Bloc transform?
- Widgets into states
- States into widgets
- Events into states Correct answer
- States into events
Explanation: Bloc processes incoming events and produces corresponding states. This unidirectional flow goes event -> state.
2 Complete the Bloc class signature
class SayacBloc extends Bloc<SayacEvent, ____> {
// ...
}
class SayacBloc extends Bloc<SayacEvent, SayacState> {
// ...
}
Explanation: Bloc takes two type parameters: the event type and the state type. The second parameter is the state class.
3 Bloc parts
| Term | Meaning |
|---|---|
Bloc |
Transforms events into states |
Event |
Change request sent to Bloc |
State |
State produced by Bloc |
emit |
Method to publish new state |