Sub topic 3
Injecting repositories and keeping data access out of the UI
This chapter assumes you know Cubit and Bloc basics, BlocProvider, Equatable, Dart Streams, and async/await.
Injecting a repository
A repository hides where data comes from. The Cubit asks the repository for data and never talks to the network or database directly. Pass the repository through the constructor so tests can swap in a fake.
RepositoryProvider<TodosRepository>(
create: (_) => InMemoryTodosRepository(),
child: BlocProvider(
create: (context) => TodosCubit(context.read<TodosRepository>())..load(),
child: const MaterialApp(home: Scaffold()),
),
)RepositoryProvider exposes the repository to its subtree. The BlocProvider below it reads that repository while it creates the Cubit.
Testing with bloc_test
blocTest builds a Cubit, runs an action, and checks the emitted states.
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
blocTest<CounterCubit, int>(
'emits [1] when increment is called',
build: CounterCubit.new,
act: (cubit) => cubit.increment(),
expect: () => [1],
);
}Controlling concurrency
Bloc handles events one at a time by default. The bloc_concurrency package adds transformers. restartable() cancels older work when a new event arrives, which suits search. droppable() ignores new events while one is running, which suits a submit button.
Under the hood: state as a Stream
Every Cubit and Bloc exposes its states as a stream. The widgets from BlocBuilder subscribe to that stream. Call close() when you finish with an instance so the stream releases its resources.
MultiBlocProvider and bloc-to-bloc communication
MultiBlocProvider declares several providers without deep nesting. A Bloc can listen to another Bloc's stream, but keep that link small, because two Blocs that depend on each other are hard to test.
Logging with BlocObserver
A BlocObserver sees every state change and error. Set it once at startup.
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
debugPrint('${bloc.runtimeType} $change');
}
}
void main() {
Bloc.observer = AppBlocObserver();
}Persisting state with HydratedBloc
HydratedBloc saves state as JSON and restores it on the next launch. You implement toJson and fromJson on the state class.
Exercise
Exercise
Why does the Cubit receive its repository through the constructor instead of creating it itself?
Show answer
The test can pass a fake repository, so the test runs without a network or database, and the Cubit never builds its own data client.