Advanced
State Management in Flutter with the BLoC Pattern
· 10 min read
What Is BLoC?
BLoC (Business Logic Component) is a design pattern aimed at fully separating the UI layer from business logic. The UI sends an event to a Bloc; the Bloc processes that event and emits a new state; the UI only listens to that state and updates itself. The UI never runs business logic directly — it only sends events and listens for state.
The flutter_bloc package brings this pattern to Flutter and offers two core classes: Bloc and Cubit. Cubit is a simpler version that produces state directly through methods without an event layer; Bloc is the full version that processes events through a stream, giving a more structured and testable flow.
A Simple Example With Cubit
For simple cases that don't need an event layer, Cubit is enough. Here's a counter example:
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}Modeling Events and States With Bloc
In more complex flows, such as a login form, modeling events and states as separate classes makes it clear in the code which event leads to which state. Using a sealed class guarantees at compile time, via switch expressions, that every subtype is handled:
sealed class AuthEvent {}
class AuthLoginRequested extends AuthEvent {
AuthLoginRequested(this.email, this.password);
final String email;
final String password;
}
class AuthLogoutRequested extends AuthEvent {}
sealed class AuthState {}
class AuthInitial extends AuthState {}
class AuthLoading extends AuthState {}
class AuthAuthenticated extends AuthState {
AuthAuthenticated(this.userId);
final String userId;
}
class AuthError extends AuthState {
AuthError(this.message);
final String message;
}
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc(this._authRepository) : super(AuthInitial()) {
on<AuthLoginRequested>(_onLoginRequested);
on<AuthLogoutRequested>((event, emit) => emit(AuthInitial()));
}
final AuthRepository _authRepository;
Future<void> _onLoginRequested(
AuthLoginRequested event,
Emitter<AuthState> emit,
) async {
emit(AuthLoading());
try {
final userId = await _authRepository.signIn(event.email, event.password);
emit(AuthAuthenticated(userId));
} catch (e) {
emit(AuthError('Sign-in failed.'));
}
}
}Note that we deliberately show a generic "Sign-in failed" message; never log or display the raw error detail or the password the user entered — that's sensitive data.
BlocProvider, BlocBuilder and BlocListener
BlocProvider injects a Bloc/Cubit instance into the widget tree. BlocBuilder rebuilds the UI whenever the state changes. BlocListener, on the other hand, reacts to state changes without building UI, used to trigger side effects such as navigation or showing a SnackBar:
BlocProvider(
create: (context) => AuthBloc(context.read<AuthRepository>()),
child: BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.message)),
);
}
},
child: BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is AuthLoading) {
return const Center(child: CircularProgressIndicator());
}
return LoginForm(
onSubmit: (email, password) => context
.read<AuthBloc>()
.add(AuthLoginRequested(email, password)),
);
},
),
),
)BLoC or Provider/Riverpod?
• Simple, local state (toggling something within a page, form state): Provider or setState is usually enough. • If dependency injection and compile-safe reactive reads come first: Riverpod. • If a large team wants an event-driven flow with a clear in/out contract and high testability: BLoC. Since every state transition is tied to an event, testing and logging the flow becomes easier. The three aren't mutually exclusive; it's common in a single project to use Provider for page-level state and Bloc for critical flows like authentication.
Things to Watch Out For
1. Don't Forget to close() Your Blocs
BlocProvider automatically closes a Bloc it created when it's removed from the widget tree. But if you created a Bloc manually outside of BlocProvider, for example inside a service class, you must call close() yourself during disposal; otherwise stream subscriptions stay open.
2. Watch for Sensitive Data When Logging With BlocObserver
BlocObserver lets you track every event and state transition across the app from a single place; it's very valuable for debugging. But if the event/state objects contain sensitive fields such as passwords or tokens, don't log them as-is; log only in debug mode and mask the sensitive fields.
Conclusion
BLoC offers a predictable, testable flow by clearly separating events and states. Use Cubit for simple cases and Bloc for complex flows; manage the UI with BlocBuilder and side effects with BlocListener. There's no need to force the whole project into BLoC; the right tool pays off when used in the right place.