Junior — Middle
Can you explain the mechanism of the BLoC pattern in managing application state?
sobes.tech AI
Answer from AI
The BLoC (Business Logic Component) pattern is used in Flutter to manage application state by separating business logic from the UI.
The main idea is to use streams to pass events and states:
- Events: user actions or external events are sent to the BLoC.
- Processing: The BLoC receives events, performs business logic, and forms a new state.
- States: the updated data is passed back through a stream, which the UI subscribes to.
This makes the code more modular, testable, and maintainable.
An example of a simplified BLoC:
class CounterBloc {
final _eventController = StreamController<void>();
final _stateController = StreamController<int>();
int _count = 0;
StreamSink<void> get eventSink => _eventController.sink;
Stream<int> get stateStream => _stateController.stream;
CounterBloc() {
_eventController.stream.listen((_) {
_count++;
_stateController.sink.add(_count);
});
}
void dispose() {
_eventController.close();
_stateController.close();
}
}
The UI subscribes to stateStream and sends events to eventSink. The BLoC updates the state and notifies the UI.