State management is one of the most debated topics in Flutter. After trying several approaches at Netglade, BLoC is the one we settled on for production apps.
What is BLoC?#
BLoC stands for Business Logic Component. It separates your UI from your business logic by using streams of events and states.
// Events
sealed class CounterEvent {}
class Increment extends CounterEvent {}
// States
class CounterState {
final int count;
const CounterState(this.count);
}
// BLoC
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(const CounterState(0)) {
on<Increment>((event, emit) => emit(CounterState(state.count + 1)));
}
}
Why BLoC Over Alternatives?#
- Testability — pure functions, easy to unit test
- Predictability — every state transition is explicit
- Scalability — works well as apps grow complex
Using BlocBuilder in UI#
BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Text('Count: ${state.count}');
},
)
BLoC is opinionated, which is a feature — it removes ambiguity about where logic lives.