D
State ManagementIntermediate30 XP4 min read

What is the BLoC pattern and why is it used in Flutter?

TL;DR: BLoC (Business Logic Component) separates UI from business logic using streams. UI sends Events to the BLoC; BLoC processes them and emits States back to the UI via a stream.

Full Answer

BLoC enforces a strict unidirectional data flow, making complex state transitions testable and predictable.

  • Event — user actions or external triggers (e.g., LoginButtonPressed)
  • State — UI representation of data (e.g., LoginLoading, LoginSuccess, LoginFailure)
  • BLoC — maps Events to States using business logic; never touches UI
  • BlocBuilder — rebuilds UI when state changes
  • BlocListener — reacts to state changes without rebuilding (e.g., showing SnackBar)
  • BlocConsumer — combines BlocBuilder + BlocListener
🎯

For simpler cases, use Cubit — a BLoC variant without events. Cubit exposes methods directly instead of using an event-to-state mapping, reducing boilerplate.

Code Examples

dartCubit (simplified BLoC)
Output
Displays 'Count: 0', increments to 'Count: 1' on button tap

Common Mistakes

  • Using BLoC when Cubit would suffice — adds unnecessary event boilerplate
  • Triggering UI effects (navigation, dialogs) from inside BLoC — use BlocListener instead

Interview Tip

💡

Explain BLoC's testing advantage: you can test every state transition by adding events and checking emitted states — completely independent of Flutter widgets.

#BLoC#stream#events#states#separation-of-concerns