Junior — Middle
Can you explain what the BLoC pattern means in application architecture?
sobes.tech AI
Answer from AI
The BLoC (Business Logic Component) pattern in Flutter application architecture is designed to separate business logic from the UI. It helps manage the application's state, making the code more modular and testable.
Main ideas of BLoC:
- Data Streams: BLoC uses streams to pass events from the UI and emit states back.
- Input Events: The UI sends events to BLoC, such as button presses.
- Output States: BLoC processes events and emits new states, which the UI subscribes to.
Example of a simple BLoC in Dart:
import 'dart:async';
class CounterBloc {
int _counter = 0;
final _stateController = StreamController<int>();
Stream<int> get counterStream => _stateController.stream;
final _eventController = StreamController<void>();
Sink<void> get incrementSink => _eventController.sink;
CounterBloc() {
_eventController.stream.listen((_) {
_counter++;
_stateController.sink.add(_counter);
});
}
void dispose() {
_stateController.close();
_eventController.close();
}
}
Here, the UI sends an event to incrementSink, the BLoC increments the counter, and sends the new value to the counterStream, which the UI subscribes to.