Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 73 ยท State management

BLoC and Cubit

Learn the BLoC pattern in Flutter with flutter_bloc: events, states and streams, Cubit versus Bloc, BlocBuilder, BlocListener, and when to choose BLoC.

BLoC stands for Business Logic Component. The idea: keep all decisions out of widgets. The UI sends events in, the BLoC thinks, and it emits a stream of states out. Widgets only draw the latest state and forward user actions. The bloc and flutter_bloc packages implement it, with a simpler variant called Cubit for when you do not need events.

BLoC is popular in large teams because the data flow is strict and every change is a visible, loggable, testable event. It is more ceremony than Provider or Riverpod, and it rests on the Dart Stream you met in Futures, async/await and Streams.

Real vs stand-in. flutter_bloc cannot run on this site, so the Dart is read-only. The JavaScript examples are stand-ins: a Cubit and a Bloc built from a plain listener list and an async iterator, so you can see the event-to-state flow.

The BLoC loop

UI event add(LoginPressed)
BLoC Decides what happens.
State stream Emits new states.
UI redraws BlocBuilder shows the state.
1 / 2

Setup

YAML
dependencies:
  flutter_bloc: ^9.0.0
  equatable: ^2.0.5

equatable makes states compare by value, which matters because BLoC skips an emit equal to the current state.

Cubit: methods and states

A Cubit<State> holds one state and exposes methods that call emit(newState):

DART
class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);          // the initial state

  void increment() => emit(state + 1);
  void reset() => emit(0);
}

Provide it with BlocProvider, which creates and closes it for you:

DART
BlocProvider(
  create: (context) => CounterCubit(),
  child: const CounterPage(),
)

Read it in widgets:

DART
class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: BlocBuilder<CounterCubit, int>(
          builder: (context, count) => Text('Count: $count'),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<CounterCubit>().increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

BlocBuilder rebuilds when the state changes. context.read<CounterCubit>() finds the cubit without subscribing (the same name and meaning as in Provider; flutter_bloc is built on it). context.watch and context.select exist as well.

Stand-in: a Cubit

JS A Cubit that skips equal states

Press Run (or Ctrl + Enter) to see the console output here.

No output.

States for real screens

A counter is a single int. Real screens have several situations, so model them as a family of state classes. Dart's sealed classes (Collections and generics) give you exhaustive switch:

DART
sealed class ProductsState extends Equatable {
  const ProductsState();
  @override
  List<Object?> get props => [];
}

class ProductsInitial extends ProductsState {
  const ProductsInitial();
}

class ProductsLoading extends ProductsState {
  const ProductsLoading();
}

class ProductsLoaded extends ProductsState {
  const ProductsLoaded(this.products);
  final List<Product> products;
  @override
  List<Object?> get props => [products];
}

class ProductsFailure extends ProductsState {
  const ProductsFailure(this.message);
  final String message;
  @override
  List<Object?> get props => [message];
}

Then a Cubit that moves between them:

DART
class ProductsCubit extends Cubit<ProductsState> {
  ProductsCubit(this._repository) : super(const ProductsInitial());

  final ProductRepository _repository;

  Future<void> load() async {
    emit(const ProductsLoading());
    try {
      emit(ProductsLoaded(await _repository.fetchProducts()));
    } catch (e) {
      emit(ProductsFailure('Could not load products'));
    }
  }
}

The widget reacts to every case, and the compiler makes sure none is forgotten:

DART
BlocBuilder<ProductsCubit, ProductsState>(
  builder: (context, state) => switch (state) {
    ProductsInitial() || ProductsLoading() =>
      const Center(child: CircularProgressIndicator()),
    ProductsLoaded(:final products) => ProductGrid(products: products),
    ProductsFailure(:final message) => Text(message),
  },
)

Bloc: events in, states out

A Bloc<Event, State> adds an explicit event layer. You register handlers with on<EventType>:

DART
sealed class CounterEvent {}
class Incremented extends CounterEvent {}
class Decremented extends CounterEvent {}

class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(0) {
    on<Incremented>((event, emit) => emit(state + 1));
    on<Decremented>((event, emit) => emit(state - 1));
  }
}

// In the UI:
context.read<CounterBloc>().add(Incremented());

What do you gain over a Cubit?

  • Traceability. onEvent, onTransition and onChange show why a state changed (event A took state X to Y). A Cubit only reports the state change.
  • Event transformers. Handlers can debounce, throttle or drop work, for example search-as-you-type with restartable(); only the latest query runs.
  • Ordering. By default events are handled one at a time in the order received (concurrent transformers are opt-in).
DART
on<SearchChanged>(
  (event, emit) async {
    emit(SearchLoading());
    emit(SearchLoaded(await repo.search(event.query)));
  },
  transformer: restartable(),   // from bloc_concurrency
);

Stand-in: a Bloc with an event queue

This stand-in processes events one at a time, in order, from a queue, and records each transition.

JS A Bloc: events processed in order, transitions logged

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The log is the BLoC selling point: every change has a cause. Note how ItemAdded waited for the slow load to finish before it ran.

BlocListener and BlocConsumer

BlocBuilder is for drawing. For one-off side effects (a snackbar, navigation, a dialog), use BlocListener, which runs a callback on state changes but does not rebuild:

DART
BlocListener<ProductsCubit, ProductsState>(
  listenWhen: (previous, current) => current is ProductsFailure,
  listener: (context, state) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text((state as ProductsFailure).message)),
    );
  },
  child: const ProductsView(),
)

BlocConsumer combines builder and listener. Both accept buildWhen / listenWhen to filter. BlocSelector rebuilds only when a derived value changes, like select in Provider.

Use MultiBlocProvider for several blocs. As with Provider, a bloc created inside one route is not visible to another, so provide it above the Navigator or pass it with BlocProvider.value.

When to choose BLoC

Choose BLoC when you have a large team, strict architecture rules, complex event flows (debounce, ordering, retries), or a need to log and replay what happened. Choose a Cubit for most screens even in BLoC projects. Prefer Provider or Riverpod when you want less boilerplate. All of them can build the same app; Choosing state management and app architecture compares them side by side.

Common mistakes

  • Mutating a state object and emitting it again: equal states are skipped, so the UI does not change. Use immutable states and copyWith.
  • Missing props in Equatable states, so changes look equal.
  • Emitting after close (for example after an await when the screen is gone). Check isClosed in long async methods.
  • Business logic in widgets or widgets calling repositories directly.
  • Using BlocBuilder for navigation or snackbars. Use BlocListener.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between a Cubit and a Bloc?

    Both emit states. A Bloc adds an event layer that gives traceability and event transformers.
  2. 2. Which widget should show a snackbar when a state is a failure?

    Listeners run side effects without rebuilding. Builders are for drawing the state.
  3. 3. Why use Equatable for state classes?

    Blocs compare the new state with the old. Value equality makes sure real changes emit and identical ones do not.
  4. 4. By default, how does a Bloc process events added quickly one after another?

    Events are handled sequentially unless you choose another transformer such as concurrent or restartable.

Summary

  • BLoC keeps logic out of widgets: events or method calls in, a stream of immutable states out.
  • A Cubit emits states from methods; a Bloc maps events to states with on<Event> and adds traceability and event transformers.
  • BlocProvider supplies and closes the bloc; BlocBuilder draws, BlocListener does side effects, BlocConsumer does both, BlocSelector narrows rebuilds.
  • Model screen states with sealed classes and Equatable, and emit new objects rather than mutating.
  • Start with Cubit; use Bloc when you need event history, debouncing or strict ordering.

Next: Choosing State Management and App Architecture