
# Bloc and Cubit

A Flutter app built with Spring for Dart can keep its state in Bloc and Cubit, of the package `flutter_bloc`. The framework has no starter for Bloc and needs none: a bloc is a class, so it is a bean. Its dependencies come by constructor injection, its lifetime is its scope, and a widget takes it from the context and gives it to Bloc's own widgets.

Everything on this page is the code of the example [`example/bloc`](https://github.com/farum-azula/spring_core_dart/tree/main/example/bloc) of the framework's repository. The observer, the events and the mixin below are code of that example, which an app copies; they are not part of the framework.

## The idea

In a Bloc app, a `BlocProvider` puts a bloc into the widget tree and closes it, and the bloc's own dependencies come from a repository provider or a service locator. In a Spring app the container already does both jobs:

- **No `BlocProvider`, no service locator.** `@Component()` on the bloc makes it a bean. What its constructor asks for is injected.
- **A widget takes the bloc from the context**: `context.bean<CounterCubit>()`.
- **Bloc's own widgets show it**: `BlocBuilder(bloc: ..., builder: ...)`, given the bean.
- **Its lifetime is its scope**: the application's for a singleton, a screen's with the `route` scope.

## Setup

`flutter_bloc` is the app's own dependency. The example uses the navigation starter, for its screens and for the `route` scope; it brings the Flutter starter.

```yaml
# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_bloc: ^9.1.1
  spring_boot_starter_flutter_navigation: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_boot_starter_test: ^0.9.0
  spring_core_dart_generator: ^0.9.0
```

## A Cubit for the whole app

`@Component()` makes the cubit a bean, one for the application (a singleton). Every screen that asks for it gets the same count.

```dart
@Component()
class CounterCubit extends Cubit<int> with ClosedWithBean<int> {
  CounterCubit() : super(0);

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

  void decrement() => emit(state - 1);

  @override
  String toString() => 'CounterCubit';
}
```

A widget takes it from the context and gives it to `BlocBuilder`:

```dart
@override
Widget build(BuildContext context) {
  final counter = context.bean<CounterCubit>();
  return Row(
    mainAxisSize: MainAxisSize.min,
    children: [
      Tap('−', onTap: counter.decrement),
      // Bloc's own widget, given the bean: no BlocProvider above.
      BlocBuilder<CounterCubit, int>(
        bloc: counter,
        builder: (context, count) =>
            Text('$count', key: const ValueKey('count')),
      ),
      Tap('+', onTap: counter.increment),
    ],
  );
}
```

`Tap` is a small widget of the example, a word to tap: the app has no design library.

## A Bloc with events, states and a service

The repository is a bean like any other:

```dart
@Service()
class BookRepository {
  final List<Book> _books = [const Book('Dune'), const Book('Neuromancer')];

  Future<List<Book>> all() async {
    await Future<void>.delayed(const Duration(milliseconds: 300));
    return List.unmodifiable(_books);
  }

  Future<void> add(String title) async {
    await Future<void>.delayed(const Duration(milliseconds: 150));
    if (_books.any((book) => book.title == title)) {
      throw StateError('"$title" is on the shelf already');
    }
    _books.add(Book(title));
  }
}
```

The bloc's events and states are plain classes:

```dart
sealed class BooksEvent {
  const BooksEvent();
}

final class BooksRequested extends BooksEvent {
  const BooksRequested();

  @override
  String toString() => 'BooksRequested';
}

final class BookAdded extends BooksEvent {
  const BookAdded(this.title);

  final String title;

  @override
  String toString() => 'BookAdded($title)';
}

sealed class BooksState {
  const BooksState();
}

final class BooksLoading extends BooksState {
  const BooksLoading();
}

final class BooksLoaded extends BooksState {
  const BooksLoaded(this.books, {this.problem});

  final List<Book> books;
  final String? problem;
}
```

The bloc gets the repository through its constructor, as any bean does. Nothing registers the bloc or its repository by hand.

```dart
@Component()
class BooksBloc extends Bloc<BooksEvent, BooksState>
    with ClosedWithBean<BooksState> {
  BooksBloc(this.repository) : super(const BooksLoading()) {
    on<BooksRequested>(_load);
    on<BookAdded>(_add);
  }

  final BookRepository repository;

  Future<void> _load(BooksRequested event, Emitter<BooksState> emit) async {
    emit(const BooksLoading());
    emit(BooksLoaded(await repository.all()));
  }

  Future<void> _add(BookAdded event, Emitter<BooksState> emit) async {
    try {
      await repository.add(event.title);
      emit(BooksLoaded(await repository.all()));
    } on StateError catch (error) {
      emit(BooksLoaded(await repository.all(), problem: error.message));
    }
  }

  @override
  String toString() => 'BooksBloc';
}
```

The screen asks for the books once, when it is first built, and shows the states:

```dart
@override
void initState() {
  super.initState();
  SpringScope.of(
    context,
    listen: false,
  ).getBean<BooksBloc>().add(const BooksRequested());
}
```

```dart
BlocBuilder<BooksBloc, BooksState>(
  bloc: context.bean<BooksBloc>(),
  builder: (context, state) => switch (state) {
    BooksLoading() => const Text('Loading the shelf…'),
    BooksLoaded(:final books, :final problem) => Column(
      children: [
        for (final book in books) Text(book.title),
        if (problem != null) Text(problem),
      ],
    ),
  },
)
```

## A Cubit of one screen

With `@Scope(NavigationScopes.route)` a cubit belongs to one screen: it is made when the screen opens and closed when the screen does. The next visit starts with a new one, empty.

```dart
@Component()
@Scope(NavigationScopes.route)
class DraftCubit extends Cubit<String> with ClosedWithBean<String> {
  DraftCubit() : super('');

  void type(String title) => emit(title);

  @override
  String toString() => 'DraftCubit';
}
```

Every widget of the screen gets the same object from the context. Another bean, here the application's `BooksBloc`, is taken the same way:

```dart
@ScreenRoute('/new', title: 'A new book')
class NewBookPage extends StatefulWidget {
  const NewBookPage({super.key});

  @override
  State<NewBookPage> createState() => _NewBookPageState();
}

class _NewBookPageState extends State<NewBookPage> {
  // ... the text controller and the focus node

  @override
  Widget build(BuildContext context) {
    // The screen's own: the same object for every widget of this screen.
    final draft = context.bean<DraftCubit>();
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        EditableText(
          // ...
          onChanged: draft.type,
        ),
        BlocBuilder<DraftCubit, String>(
          bloc: draft,
          builder: (context, title) => Text(
            title.isEmpty ? 'Type a title' : 'Title: $title',
            key: const ValueKey('draft'),
          ),
        ),
        Tap(
          'Add',
          onTap: () {
            if (draft.state.isNotEmpty) {
              context.bean<BooksBloc>().add(BookAdded(draft.state));
            }
            context.route.pop();
          },
        ),
      ],
    );
  }
}
```

See [Beans per screen or branch](../components/spring-boot-starter-flutter-navigation/scopes.md) for the scope.

## Closing a bloc

The container does not close a bloc by itself: a bean's `close()` is not called when a component is destroyed. So each bloc of the example has a mixin with one `@PreDestroy` method. This is the whole of it:

```dart
import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:spring_boot_starter_flutter_navigation/spring_boot_starter_flutter_navigation.dart';

mixin ClosedWithBean<S> on BlocBase<S> {
  @PreDestroy()
  void closeWithBean() => unawaited(close());
}
```

The container calls it when the bean is destroyed: with the application for a bloc of the app, with the screen for one of the `route` scope. No widget calls `close()`.

The method is synchronous and does not await `close()`. A screen's beans (the `route` scope) are destroyed at once when the screen closes, and a destroy callback that returns a `Future` there is reported by the container as not awaited. Nothing is lost by it: a bloc refuses new events and states from the moment `close` is called.

```dart
test('the container closes the blocs with the application', () async {
  final previous = Bloc.observer;
  final context = await springApplication.runAsync(const []);
  final counter = context.getBean<CounterCubit>();
  final books = context.getBean<BooksBloc>();
  expect(counter.isClosed, isFalse);

  await context.closeAsync();

  expect(counter.isClosed, isTrue);
  expect(books.isClosed, isTrue);
  expect(Bloc.observer, same(previous));
});
```

See [@PreDestroy](../components/spring-core-dart/beans/pre-destroy.md).

## Bloc's events as application events

Bloc has one observer for the whole app, `Bloc.observer`. In the example the observer is a bean that publishes what every bloc does as application events. Three event classes carry it:

```dart
sealed class BlocApplicationEvent extends ApplicationEvent {
  BlocApplicationEvent(BlocBase<Object?> super.bloc);

  BlocBase<Object?> get bloc => source as BlocBase<Object?>;
}

final class BlocEventAdded extends BlocApplicationEvent {
  BlocEventAdded(super.bloc, this.event);

  final Object? event;

  @override
  String get eventName => 'BlocEventAdded';
}

final class BlocStateChanged extends BlocApplicationEvent {
  BlocStateChanged(super.bloc, {required this.current, required this.next});

  final Object? current;
  final Object? next;

  @override
  String get eventName => 'BlocStateChanged';
}

final class BlocFailed extends BlocApplicationEvent {
  BlocFailed(super.bloc, this.error, this.stackTrace);

  final Object error;
  final StackTrace stackTrace;

  @override
  String get eventName => 'BlocFailed';
}
```

| Event | When | It carries |
|---|---|---|
| `BlocEventAdded` | An event was added to a Bloc (a Cubit has none) | `bloc`, `event` |
| `BlocStateChanged` | A bloc or a cubit went from one state to another | `bloc`, `current`, `next` |
| `BlocFailed` | A bloc reported an error (`addError`, or one thrown in a handler) | `bloc`, `error`, `stackTrace` |

The observer:

```dart
@Component()
class SpringBlocObserver extends BlocObserver
    implements BeanFactoryPostProcessor, ApplicationEventPublisherAware {
  late ApplicationEventPublisher events;

  @override
  void setApplicationEventPublisher(ApplicationEventPublisher publisher) =>
      events = publisher;

  BlocObserver? _previous;

  @override
  void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    _previous = Bloc.observer;
    Bloc.observer = this;
  }

  @PreDestroy()
  void uninstall() {
    if (identical(Bloc.observer, this) && _previous != null) {
      Bloc.observer = _previous!;
    }
    _previous = null;
  }

  @override
  void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
    super.onEvent(bloc, event);
    events.publishEvent(BlocEventAdded(bloc, event));
  }

  @override
  void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
    super.onChange(bloc, change);
    events.publishEvent(
      BlocStateChanged(
        bloc,
        current: change.currentState,
        next: change.nextState,
      ),
    );
  }

  @override
  void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
    super.onError(bloc, error, stackTrace);
    events.publishEvent(BlocFailed(bloc, error, stackTrace));
  }
}
```

It is a `BeanFactoryPostProcessor` for one reason: a bloc keeps the observer there was when it was made. So the observer must take its place before the first bloc is created, and the container runs a `BeanFactoryPostProcessor` before it makes any other bean. When the application closes, the `@PreDestroy` method gives the place back, unless something else took it since.

The publisher does not come through the constructor: a post-processor is made too early for ordinary injection. `ApplicationEventPublisherAware` is the usual way to give such a bean the publisher: the container calls `setApplicationEventPublisher`. The bean factory itself publishes no events; the application context does.

A bean then hears the blocs with `@EventListener`. It subscribes to no bloc and knows nothing of streams. A `condition` keeps a method to one bloc:

```dart
bool ofCounter(BlocStateChanged change) => change.bloc is CounterCubit;

@Service()
class Journal extends ChangeNotifier {
  final List<String> _lines = [];

  int counterChanges = 0;

  List<String> get lines => List.unmodifiable(_lines.reversed.take(8));

  @EventListener()
  void onEvent(BlocEventAdded added) =>
      _write('${added.bloc} ← ${added.event}');

  @EventListener()
  void onChange(BlocStateChanged change) => _write(
    '${change.bloc}: ${change.current} → ${change.next}',
  );

  @EventListener(condition: ofCounter)
  void onCounter(BlocStateChanged change) => counterChanges++;

  @EventListener()
  void onFailure(BlocFailed failed) =>
      _write('${failed.bloc} failed: ${failed.error}');

  void _write(String line) {
    _lines.add(line);
    notifyListeners();
  }
}
```

See [@EventListener](../components/spring-core-dart/events/event-listener.md) and [BeanFactoryPostProcessor](../components/spring-core-dart/beans/bean-factory-post-processor.md).

## What stays Bloc's own way

A Spring widget (`SpringStatelessWidget`) does not rebuild by a bloc's state on its own: a bloc is a stream, not a `Listenable`. So the widgets that rebuild by a bloc's state are Bloc's, used as usual: `BlocBuilder` and `BlocSelector`, given the bean with `bloc:`.

The `Journal` above is a `ChangeNotifier`, so the example shows it with Flutter's `ListenableBuilder`. For state without Bloc, in beans that rebuild Spring widgets by themselves, see [State beans](../components/spring-boot-starter-flutter/state-beans.md).

## Tests

`springBootTest` starts the application's beans, and `BeanOverride` puts a repository of the test in place of the app's:

```dart
class _Shelf extends BookRepository {
  final List<Book> books = [const Book('Solaris')];

  @override
  Future<List<Book>> all() async => List.of(books);

  @override
  Future<void> add(String title) async => books.add(Book(title));
}

void main() {
  group('the beans', () {
    final app = springBootTest(
      springApplication,
      overrides: [BeanOverride<BookRepository>(_Shelf())],
    );

    test('a cubit is one bean for the app', () {
      final counter = app.getBean<CounterCubit>();
      expect(app.getBean<CounterCubit>(), same(counter));
      counter.increment();
      expect(counter.state, 1);
    });

    test('a bloc gets its repository by injection', () async {
      final books = app.getBean<BooksBloc>();
      expect(books.repository, isA<_Shelf>());

      books.add(const BooksRequested());
      final loaded = await books.stream.firstWhere(
        (state) => state is BooksLoaded,
      ) as BooksLoaded;
      expect(loaded.books.single.title, 'Solaris');
    });

    test('what a bloc does is heard as application events', () async {
      final journal = app.getBean<Journal>();
      final before = journal.counterChanges;

      app.getBean<CounterCubit>().increment();
      final books = app.getBean<BooksBloc>()..add(const BookAdded('Ubik'));
      await books.stream.firstWhere(
        (state) => state is BooksLoaded && state.books.length == 2,
      );

      expect(journal.counterChanges, before + 1);
      expect(journal.lines, contains('BooksBloc ← BookAdded(Ubik)'));
      expect(Bloc.observer, same(app.getBean<SpringBlocObserver>()));
    });
  });
}
```

A widget test starts the whole app and looks at the screens. It shows the screen's cubit closed with the screen, and a new one on the next visit:

```dart
testWidgets('a screen has a cubit of its own', (tester) async {
  await tester.pumpWidget(
    SpringApplicationWidget(application: () => springApplication),
  );
  await tester.pumpAndSettle(const Duration(milliseconds: 400));
  expect(find.text('Dune'), findsOneWidget);

  await tester.tap(find.text('+'));
  await tester.pump();
  expect(
    tester.widget<Text>(find.byKey(const ValueKey('count'))).data,
    '1',
  );

  await tester.tap(find.text('Add a book'));
  await tester.pumpAndSettle();
  final first = SpringScope.beanOf<DraftCubit>(
    tester.element(find.byType(NewBookPage)),
  );
  await tester.enterText(find.byType(EditableText), 'Hyperion');
  await tester.pump();
  expect(first.state, 'Hyperion');

  await tester.tap(find.text('Add'));
  await tester.pumpAndSettle(const Duration(milliseconds: 600));
  expect(find.text('Hyperion'), findsOneWidget);
  // Leaving the screen closed its cubit.
  expect(first.isClosed, isTrue);

  // The next visit starts with a new one, empty.
  await tester.tap(find.text('Add a book'));
  await tester.pumpAndSettle();
  final second = SpringScope.beanOf<DraftCubit>(
    tester.element(find.byType(NewBookPage)),
  );
  expect(second, isNot(same(first)));
  expect(second.state, '');
});
```

See [Testing in spring_boot_starter_flutter](../components/spring-boot-starter-flutter/testing.md) and [BeanOverride and @TestBean](../components/spring-boot-starter-test/bean-override.md).

## Names in a release build

A release build shortens class names: `runtimeType` prints `minified:Class…`. The journal writes the bloc into its lines, so the example's blocs and events override `toString`:

```dart
@override
String toString() => 'CounterCubit';
```

## What the framework gives here

| For a bloc | From the framework |
|---|---|
| Its dependencies | Constructor injection: `@Component()` on the bloc, `@Service()` on the repository |
| Its place in the widgets | `context.bean<T>()`, in place of `BlocProvider` |
| One for the app, or one per screen | Scopes: a singleton, or `@Scope(NavigationScopes.route)` |
| `close()` | `@PreDestroy`, called when the bean is destroyed |
| A place for the observer before any bloc | `BeanFactoryPostProcessor`, with `ApplicationEventPublisherAware` for the publisher |
| Its events heard by other beans | `ApplicationEventPublisher` and `@EventListener`, with a `condition` |
| A fake repository in tests | `springBootTest` and `BeanOverride` |

Bloc itself, its widgets and its observer are `flutter_bloc`'s. The whole app, with its tests, is [`example/bloc`](https://github.com/farum-azula/spring_core_dart/tree/main/example/bloc).

## See also

- [State beans](../components/spring-boot-starter-flutter/state-beans.md)
- [Signals beside ChangeNotifier](../components/spring-boot-starter-flutter-signals/beside-change-notifier.md)
- [Beans in widgets](../components/spring-boot-starter-flutter/beans-in-widgets.md)
- [Beans per screen or branch](../components/spring-boot-starter-flutter-navigation/scopes.md)
- [@EventListener](../components/spring-core-dart/events/event-listener.md)
- [Inversion of control and DI](inversion-of-control.md)
