Flutter & Dart (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How does the BLoC (Business Logic Component) Pattern work?
senior LevelCode ExampleComponentsSystem Design
In Simple Words: Enforces unidirectional reactive data flow:
- UI triggers an Event (e.g.
LoginButtonPressed(email, password)). - The BLoC receives the event, executes business logic (API call), and emits new immutable States (
LoginLoading->LoginSuccess). - The UI listens via
BlocBuilderorBlocConsumerand re-renders according to the current state.
- Zero business logic inside UI widgets!
dart
// BLoC Event & State:
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository repo;
AuthBloc(this.repo) : super(AuthInitial()) {
on<LoginSubmitted>((event, emit) async {
emit(AuthLoading());
try {
final user = await repo.login(event.email, event.pass);
emit(AuthSuccess(user));
} catch (e) {
emit(AuthFailure(e.toString()));
}
});
}
}