Skip to main content

03 - BLoC Pattern in Depth: Events, States and Cubit

Cubit or Bloc? Sealed events and states, concurrency transformers, the screen, tests and persistence with hydrated_bloc, with Dart code that was run.

What do you think about this article?

At a Glance

Cubit or Bloc? Sealed events and states, concurrency transformers, the screen, tests and persistence with hydrated_bloc, with Dart code that was run.

Cubit or Bloc: start with the simplest thing that holds

Use a Cubit when state changes by calling a method and the resulting value is all you need to know; move to a Bloc when you need to know which event caused the change, or when you have to govern concurrency between events that arrive close together. The Bloc concepts guide gives the same advice: if you are not sure, start with a Cubit and promote it to a Bloc when needed. It is not a painful promotion, because state and screen stay the same: only the way transitions are triggered changes.

If you come from the comparison with Riverpod, the article Riverpod 3.0 versus BLoC 9 gives the criterion for choosing between the two libraries; here we assume you have chosen BLoC and look at how to use it well. The examples are Dart code compiled and run with Dart 3.12.2 and with bloc 9.2.1, flutter_bloc 9.1.1, bloc_concurrency 0.3.0 and hydrated_bloc 11.0.0, the versions resolved by pub on 2026-11-12. The exceptions are the screen and the test, which require Flutter: I analysed them with flutter analyze (no errors) but did not run them.

The Cubit: a counter that never goes below zero

The example is the quantity selector next to a product: plus, minus, and never a negative number. A Cubit extends Cubit<State>, starts from an initial state passed to super and changes state by calling emit. The if (state > 0) check is the business rule, and it lives in the Cubit and not in the widget: that way it holds for any screen that uses it and can be tested without a UI.

Cubit: the quantity selector
import 'package:bloc/bloc.dart';

/// The counter next to a product: it cannot go below zero.
class QuantityCubit extends Cubit<int> {
  QuantityCubit() : super(0);

  void increment() => emit(state + 1);

  void decrement() {
    if (state > 0) emit(state - 1);
  }

  @override
  void onChange(Change<int> change) {
    print('${change.currentState} -> ${change.nextState}');
    super.onChange(change);
  }
}

Future<void> main() async {
  final cubit = QuantityCubit();
  cubit.increment();
  cubit.increment();
  cubit.decrement();
  cubit.decrement();
  cubit.decrement(); // already at zero: no emission
  await cubit.close();
}

// Output:
// 0 -> 1
// 1 -> 2
// 2 -> 1
// 1 -> 0

The output shows four transitions even though the methods were called five times: the last decrement finds the state at zero and emits nothing. The onChange method is the point where a Cubit lets you observe every change; but it receives only the previous and the next state, not the reason. If at some point you ask yourself "who pushed this number to zero?", the Cubit has no answer and a Bloc does.

The Bloc: events and states as sealed types

The problem to solve is a cart with a flow that can fail: I add items, I start the payment, the payment can be declined and I must be able to start over from the cart. Events are the inputs (CartItemAdded, CartCheckoutStarted), states are the outputs. Both are sealed, a Dart 3 keyword and not a package one: the compiler knows all the subtypes and requires every switch to cover them, as the class modifiers documentation explains.

Two choices in the listing deserve a word. Amounts are integers in cents and not double: with binary decimals, sums of prices such as 0.1 + 0.2 do not give exactly 0.3, and for money that is a defect you discover late. And the CartError state carries the cart you started from (recoverable), so recovery is a normal event and not a trick.

Bloc: the cart with a payment that can fail
import 'package:bloc/bloc.dart';

class Product {
  const Product(this.id, this.name, this.priceCents);
  final String id;
  final String name;
  final int priceCents;
}

class CartItem {
  const CartItem(this.product, this.quantity);
  final Product product;
  final int quantity;
  int get totalCents => product.priceCents * quantity;
}

sealed class CartEvent {}

final class CartItemAdded extends CartEvent {
  CartItemAdded(this.product);
  final Product product;
}

final class CartCheckoutStarted extends CartEvent {}

final class CartCheckoutRetried extends CartEvent {}

sealed class CartState {}

final class CartEmpty extends CartState {}

final class CartLoaded extends CartState {
  CartLoaded(this.items);
  final List<CartItem> items;
  int get totalCents => items.fold(0, (sum, i) => sum + i.totalCents);
}

final class CartCheckoutInProgress extends CartState {
  CartCheckoutInProgress(this.items);
  final List<CartItem> items;
}

final class CartCheckoutSuccess extends CartState {
  CartCheckoutSuccess(this.orderId);
  final String orderId;
}

final class CartError extends CartState {
  CartError(this.message, this.recoverable);
  final String message;
  final CartLoaded recoverable; // the state to go back to
}

typedef CreateOrder = Future<String> Function(List<CartItem> items);

class CartBloc extends Bloc<CartEvent, CartState> {
  CartBloc({required CreateOrder createOrder})
      : _createOrder = createOrder,
        super(CartEmpty()) {
    on<CartItemAdded>(_onItemAdded);
    on<CartCheckoutStarted>(_onCheckout);
    on<CartCheckoutRetried>(_onRetried);
  }

  final CreateOrder _createOrder;

  void _onItemAdded(CartItemAdded event, Emitter<CartState> emit) {
    final current = switch (state) {
      CartLoaded(:final items) => items,
      _ => const <CartItem>[],
    };
    final index = current.indexWhere((i) => i.product.id == event.product.id);
    final updated = [...current];
    if (index >= 0) {
      updated[index] = CartItem(event.product, current[index].quantity + 1);
    } else {
      updated.add(CartItem(event.product, 1));
    }
    emit(CartLoaded(updated));
  }

  Future<void> _onCheckout(CartCheckoutStarted event, Emitter<CartState> emit) async {
    final current = state;
    if (current is! CartLoaded) return;
    emit(CartCheckoutInProgress(current.items));
    try {
      emit(CartCheckoutSuccess(await _createOrder(current.items)));
    } catch (error) {
      emit(CartError('Payment failed: $error', current));
    }
  }

  void _onRetried(CartCheckoutRetried event, Emitter<CartState> emit) {
    final current = state;
    if (current is CartError) emit(current.recoverable);
  }

  @override
  void onTransition(Transition<CartEvent, CartState> transition) {
    print('${transition.event.runtimeType}: ${transition.currentState.runtimeType} -> ${transition.nextState.runtimeType}');
    super.onTransition(transition);
  }
}

Future<void> main() async {
  const pen = Product('p1', 'Pen', 250);
  const notebook = Product('p2', 'Notebook', 480);
  var attempts = 0;
  final bloc = CartBloc(createOrder: (items) async {
    attempts++;
    if (attempts == 1) throw StateError('card declined');
    return 'ORD-$attempts';
  });

  Future<void> pause() => Future<void>.delayed(const Duration(milliseconds: 20));

  bloc
    ..add(CartItemAdded(pen))
    ..add(CartItemAdded(notebook))
    ..add(CartItemAdded(pen));
  await pause();
  print('total: ${(bloc.state as CartLoaded).totalCents} cents');

  bloc.add(CartCheckoutStarted());
  await pause();
  bloc.add(CartCheckoutRetried());
  await pause();
  bloc.add(CartCheckoutStarted());
  await pause();
  await bloc.close();
}

// Output:
// CartItemAdded: CartEmpty -> CartLoaded
// CartItemAdded: CartLoaded -> CartLoaded
// CartItemAdded: CartLoaded -> CartLoaded
// total: 980 cents
// CartCheckoutStarted: CartLoaded -> CartCheckoutInProgress
// CartCheckoutStarted: CartCheckoutInProgress -> CartError
// CartCheckoutRetried: CartError -> CartLoaded
// CartCheckoutStarted: CartLoaded -> CartCheckoutInProgress
// CartCheckoutStarted: CartCheckoutInProgress -> CartCheckoutSuccess

Read the output from the top: three additions take you from CartEmpty to CartLoaded (the total is 2 pens and a notebook, 2 × 250 + 480 = 980 cents). The first checkout goes through CartCheckoutInProgress and ends in CartError because the fake createOrder function throws on the first call. The CartCheckoutRetried event brings the state back to the cart, and the second checkout reaches CartCheckoutSuccess. In the _onCheckout handler the line that emits CartCheckoutInProgress comes before the await: if you moved it after, two taps close together would both see a CartLoaded cart and would start two payments.

A frequent temptation is to bring the state back from the screen by calling bloc.emit(previousState). Don't: emit is marked as visible only to tests and the analyzer says so (invalid_use_of_visible_for_testing_member, tried on this project). The reason is architectural: if the screen writes the state, the sequence of events no longer tells the truth, and the advantage of the Bloc vanishes. Here the return to the cart is the CartCheckoutRetried event, which shows up in the trace like all the others.

Two events together: choosing the transformer

By default a Bloc processes events of the same type in parallel: as soon as one arrives, its handler starts without waiting for the others. To change the rule you pass an EventTransformer to on. The bloc_concurrency package provides four, and the most honest way to understand them is to watch them: I sent two close Tap events to a Bloc for each one, with a handler that lasts 30 milliseconds.

The four transformers facing the same double tap
import 'package:bloc/bloc.dart';
import 'package:bloc_concurrency/bloc_concurrency.dart';

class Tap {}

class TapBloc extends Bloc<Tap, int> {
  TapBloc(String name, EventTransformer<Tap>? transformer) : super(0) {
    var n = 0;
    on<Tap>((event, emit) async {
      final id = ++n;
      print('$name: start $id');
      await Future<void>.delayed(const Duration(milliseconds: 30));
      print('$name: end $id');
      emit(state + 1);
    }, transformer: transformer);
  }
}

Future<void> main() async {
  final blocs = {
    'default': TapBloc('default', null),
    'concurrent': TapBloc('concurrent', concurrent()),
    'sequential': TapBloc('sequential', sequential()),
    'droppable': TapBloc('droppable', droppable()),
    'restartable': TapBloc('restartable', restartable()),
  };
  for (final entry in blocs.entries) {
    entry.value
      ..add(Tap())
      ..add(Tap());
    await Future<void>.delayed(const Duration(milliseconds: 150));
    print('${entry.key}: final state ${entry.value.state}');
    await entry.value.close();
  }
}

// Output:
// default: start 1
// default: start 2
// default: end 1
// default: end 2
// default: final state 2
// concurrent: start 1
// concurrent: start 2
// concurrent: end 1
// concurrent: end 2
// concurrent: final state 2
// sequential: start 1
// sequential: end 1
// sequential: start 2
// sequential: end 2
// sequential: final state 2
// droppable: start 1
// droppable: end 1
// droppable: final state 1
// restartable: start 1
// restartable: start 2
// restartable: end 1
// restartable: end 2
// restartable: final state 1

The output is deterministic in order, even though the real durations depend on the machine. With the default behaviour and with concurrent the two handlers overlap; with sequential the second starts when the first has finished; with droppable the second event is discarded; with restartable the second takes over and only its emit counts. Note this well: in the restartable case the first handler still prints "end 1", because the code inside the handler is not interrupted, only its emit is ignored. If there were a write to the server in there, it would happen twice.

The bloc_concurrency page defines the four transformers like this: concurrent processes events in parallel, sequential one after the other, droppable ignores events that arrive while one is running, restartable keeps only the last one and cancels the previous handlers.

  • Payment or order submission: droppable, because the second tap is a user mistake and must not run.
  • Search while typing: restartable, because only the last text matters.
  • Changes that add up (plus/minus): sequential, because order matters and none must be lost.
  • Independent reads: the default (parallel) is fine.

The choice depends on what happens if two events overlap. If the second makes the first useless, restartable; if the second is an accidental duplicate, droppable; if both must take effect and in order, sequential. In the earlier cart, for the payment the right choice is droppable and not sequential: with the latter the second tap would be executed after the first.

The screen: BlocConsumer and side effects

BlocConsumer joins two roles that must be kept distinct: the builder draws the screen as a function of the state, the listener performs one-off actions (navigating, showing a message) that must not repeat on every rebuild. The listenWhen parameter, described in the flutter_bloc guide, receives the previous and the current state and decides whether to call the listener: here we limit it to the two states that require an action.

The cart page (analysed with flutter analyze, not run)
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'cart_bloc.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CartBloc, CartState>(
      listenWhen: (previous, current) => current is CartCheckoutSuccess || current is CartError,
      listener: (context, state) {
        switch (state) {
          case CartCheckoutSuccess(:final orderId):
            Navigator.of(context).pushReplacementNamed('/confirmation', arguments: orderId);
          case CartError(:final message):
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
            context.read<CartBloc>().add(CartCheckoutRetried());
          default:
            break;
        }
      },
      builder: (context, state) => Scaffold(
        appBar: AppBar(title: const Text('Cart')),
        body: switch (state) {
          CartEmpty() => const Center(child: Text('The cart is empty')),
          CartLoaded(:final items, :final totalCents) => Column(children: [
              for (final i in items) ListTile(title: Text(i.product.name), trailing: Text('${i.quantity}')),
              Text('Total: ${(totalCents / 100).toStringAsFixed(2)} €'),
            ]),
          CartCheckoutInProgress() => const Center(child: CircularProgressIndicator()),
          CartCheckoutSuccess() => const SizedBox.shrink(),
          CartError(:final message) => Center(child: Text(message)),
        },
      ),
    );
  }
}

In the body switch there is no default branch, and that is deliberate: if you add a state, the page stops compiling until you decide how to show it. The listener, on the other hand, uses default: break because it handles only two cases. This block requires a Flutter app: the check done is static, flutter analyze reports no errors on this file, but I did not launch it on a device.

Testing with bloc_test

Testing a Bloc is one sentence: given this starting state (seed), when this event happens (act), then the sequence of states is this (expect). The sequence is exactly the trace you saw in the cart output, and that is why Bloc tests are easier to read than those of a class with methods.

Two tests with blocTest (written and analysed, not run)
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:fa/cart_bloc.dart';

void main() {
  const pen = Product('p1', 'Pen', 250);

  blocTest<CartBloc, CartState>(
    'adding a pen emits a cart with one item worth 250 cents',
    build: () => CartBloc(createOrder: (_) async => 'ORD-1'),
    act: (bloc) => bloc.add(CartItemAdded(pen)),
    expect: () => [
      isA<CartLoaded>()
          .having((s) => s.items.length, 'items', 1)
          .having((s) => s.totalCents, 'total', 250),
    ],
  );

  blocTest<CartBloc, CartState>(
    'a declined payment leads to CartError and keeps the cart',
    build: () => CartBloc(createOrder: (_) async => throw StateError('declined')),
    seed: () => CartLoaded([const CartItem(pen, 1)]),
    act: (bloc) => bloc.add(CartCheckoutStarted()),
    expect: () => [
      isA<CartCheckoutInProgress>(),
      isA<CartError>().having((s) => s.recoverable.items.length, 'saved items', 1),
    ],
  );
}

I did not run these tests, so the block falls into the category "output deduced, not run". The code is self-contained and flutter analyze accepts it. The second test uses seed to start directly from a cart with one item without having to repeat the addition, and the createOrder function that throws simulates the declined payment with no need for mock-object libraries.

Persistence with hydrated_bloc

A cart that disappears when the app is closed loses sales. HydratedBloc automatically saves the state on every change and restores it on creation: you only provide toJson and fromJson. Before creating any bloc you must assign HydratedBloc.storage. Since version 10.0.0 the HydratedStorage.build constructor accepts a HydratedStorageDirectory and no longer a Directory from dart:io, as the package changelog reports: many examples online, which pass the documents folder directly, do not compile with version 11.

State survives recreating the Bloc
import 'dart:io';

import 'package:hydrated_bloc/hydrated_bloc.dart';

import 'cart_bloc.dart';

class HydratedCartBloc extends HydratedBloc<CartEvent, CartState> {
  HydratedCartBloc() : super(CartEmpty()) {
    on<CartItemAdded>((event, emit) {
      final items = switch (state) {
        CartLoaded(:final items) => items,
        _ => const <CartItem>[],
      };
      emit(CartLoaded([...items, CartItem(event.product, 1)]));
    });
  }

  @override
  CartState? fromJson(Map<String, dynamic> json) {
    try {
      final items = (json['items'] as List).cast<Map<String, dynamic>>().map((m) {
        return CartItem(
          Product(m['id'] as String, m['name'] as String, (m['priceCents'] as num).toInt()),
          (m['quantity'] as num).toInt(),
        );
      }).toList();
      return CartLoaded(items);
    } catch (_) {
      return null; // unreadable data: start again from the initial state
    }
  }

  @override
  Map<String, dynamic>? toJson(CartState state) {
    if (state is! CartLoaded) return null; // the other states are not saved
    return {
      'items': [
        for (final i in state.items)
          {
            'id': i.product.id,
            'name': i.product.name,
            'priceCents': i.product.priceCents,
            'quantity': i.quantity,
          },
      ],
    };
  }
}

Future<void> main() async {
  final dir = Directory.systemTemp.createTempSync('hydrated_demo');
  HydratedBloc.storage = await HydratedStorage.build(
    storageDirectory: HydratedStorageDirectory(dir.path),
  );

  final first = HydratedCartBloc();
  first.add(CartItemAdded(const Product('p1', 'Pen', 250)));
  await Future<void>.delayed(const Duration(milliseconds: 20));
  print('before: ${first.state.runtimeType}');
  await first.close();

  final second = HydratedCartBloc(); // simulates the app restart
  print('after restart: ${second.state.runtimeType}, '
      '${(second.state as CartLoaded).items.length} item');
  await second.close();
  dir.deleteSync(recursive: true);
}

// Output:
// before: CartLoaded
// after restart: CartLoaded, 1 item

The output demonstrates the cycle: the first Bloc receives an item and is closed, the second (which simulates the app restart) starts already with a one-item CartLoaded, read from disk. Three details avoid the most common failures. toJson returns null for transient states, which are therefore not saved. Numbers are read with (x as num).toInt() because the JSON format does not distinguish integers from decimals (the syntax of numbers is defined in RFC 8259), and a direct cast to double or int can fail depending on how the value was written. And fromJson must be able to throw without consequences: if the saved format is old, the package catches the error and, by default (HydrationErrorBehavior.overwrite, described in the enum documentation), overwrites the saved data at the next state change.

This behaviour has a cost you should know: if you release a version that changes the cart fields, carts saved in the previous format are lost at the first state change. For a cart that is fine, for a long form to fill in perhaps not: in that case the way is HydrationErrorBehavior.retain and an explicit migration in fromJson, reading a version field.

What you can do now

You can decide between Cubit and Bloc from the question "do I need the reason for the change?", design sealed events and states so that the compiler flags every forgotten case, choose the transformer from the behaviour you want when two events overlap, and restore state after an error without writing it from the screen. To measure the speed of the screen you built, move on to Performance and jank; to organise these Blocs into folders and layers read feature-first architecture; to learn why the screen rebuilds on every state, Flutter internals; for tests on the real screen, widget testing and golden tests.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects