Riverpod 3.0 or BLoC 9: the choice depends on how you want state to change
Choose Riverpod when your state is mostly data that comes from an asynchronous source and that several screens must read, filter and invalidate. Choose BLoC when you need every state change to have a name, an event that caused it and a trace you can log, replay or test as a sequence. Both libraries work, and neither is "the right one" in absolute terms: they answer a different question. Riverpod asks "which data does this value depend on?", BLoC asks "which event made this state change?".
Take a concrete case: the task list of a management app. It loads from the server, you add an item, and
the screen shows loading, the list or an error. Here we implement it twice, with Riverpod 3 and with
BLoC 9, in two Dart files that run from the command line without Flutter, so you can run them and see
what really happens. The versions used are the ones resolved by pub on 2026-11-12: the
riverpod page on pub.dev lists 3.5.0 and the one for
bloc lists 9.2.1. If you come from the architecture articles,
article 11 shows where these objects
live in a real project.
The same feature with Riverpod: an AsyncNotifier
The problem: the list is asynchronous, so every read can be in one of three situations (in progress,
succeeded, failed) and the code must not forget any of them. Riverpod models the case with
AsyncValue, and an AsyncNotifier class produces it in the build
method. Here the fake repository simulates a network call with a 10 millisecond delay and counts the calls.
import 'dart:async';
import 'package:riverpod/riverpod.dart';
class TaskRepository {
final List<String> _archive = ['Write the report', 'Review the PR'];
int calls = 0;
Future<List<String>> fetchTasks() async {
calls++;
await Future<void>.delayed(const Duration(milliseconds: 10));
return List.unmodifiable(_archive);
}
Future<void> createTask(String title) async {
await Future<void>.delayed(const Duration(milliseconds: 10));
_archive.add(title);
}
}
final taskRepositoryProvider = Provider<TaskRepository>((ref) => TaskRepository());
class TaskList extends AsyncNotifier<List<String>> {
@override
Future<List<String>> build() => ref.read(taskRepositoryProvider).fetchTasks();
Future<void> add(String title) async {
final repo = ref.read(taskRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repo.createTask(title);
return repo.fetchTasks();
});
}
}
final taskListProvider =
AsyncNotifierProvider<TaskList, List<String>>(TaskList.new);
Future<void> main() async {
final container = ProviderContainer();
container.listen(taskListProvider, (previous, next) {
print('state: $next');
});
final first = await container.read(taskListProvider.future);
print('loaded: ${first.length}');
await container.read(taskListProvider.notifier).add('Send the invoice');
print('now: ${container.read(taskListProvider).requireValue}');
container.dispose();
}
// Output:
// state: AsyncData<List<String>>(value: [Write the report, Review the PR])
// loaded: 2
// state: AsyncLoading<List<String>>(value: [Write the report, Review the PR])
// state: AsyncData<List<String>>(value: [Write the report, Review the PR, Send the invoice])
// now: [Write the report, Review the PR, Send the invoice]
Four lines matter. build returns the repository's Future: Riverpod runs it on
the first read and keeps the result. add sets AsyncLoading, then calls
AsyncValue.guard, which turns an exception into AsyncError instead of letting it
escape. The repository is read with ref.read before the first await because a
Ref used after its provider has been destroyed throws an exception in Riverpod 3 (we see it
below). The output shows a surprising detail: during the following load the state is
AsyncLoading but still keeps the previous value, so the screen can show the old list with an
indicator instead of going blank.
If you remove AsyncValue.guard and the repository throws, the error leaves the method and the
state stays stuck on AsyncLoading. The
main uses a ProviderContainer because providers are plain Dart objects and
need no widgets; the ProviderContainer.test constructor, on the other hand, exists only for
tests, and outside a test the compiler warns (invalid_use_of_visible_for_testing_member) and
at runtime it throws Bad state: addTearDown() may only be called within a test. Both
messages come from running this example.
The same feature with BLoC: events, states, transitions
With BLoC the screen does not call a method: it adds an event. The Bloc receives it,
processes it in a handler registered with on<Event> and emits zero or more states. The
cost is writing three sets of types (events, states, bloc); the benefit is that the history of what
happened is made of named objects and not of method calls.
import 'package:bloc/bloc.dart';
sealed class TaskEvent {}
final class TasksRequested extends TaskEvent {}
final class TaskAdded extends TaskEvent {
TaskAdded(this.title);
final String title;
}
sealed class TaskState {}
final class TaskInitial extends TaskState {}
final class TaskLoading extends TaskState {}
final class TaskLoaded extends TaskState {
TaskLoaded(this.tasks);
final List<String> tasks;
}
final class TaskFailure extends TaskState {
TaskFailure(this.message);
final String message;
}
class TaskBloc extends Bloc<TaskEvent, TaskState> {
TaskBloc() : super(TaskInitial()) {
on<TasksRequested>(_onRequested);
on<TaskAdded>(_onAdded);
}
final List<String> _archive = ['Write the report', 'Review the PR'];
Future<void> _onRequested(TasksRequested event, Emitter<TaskState> emit) async {
emit(TaskLoading());
await Future<void>.delayed(const Duration(milliseconds: 10));
emit(TaskLoaded(List.unmodifiable(_archive)));
}
Future<void> _onAdded(TaskAdded event, Emitter<TaskState> emit) async {
emit(TaskLoading());
await Future<void>.delayed(const Duration(milliseconds: 10));
_archive.add(event.title);
emit(TaskLoaded(List.unmodifiable(_archive)));
}
@override
void onTransition(Transition<TaskEvent, TaskState> t) {
print('${t.event.runtimeType}: ${t.currentState.runtimeType} -> ${t.nextState.runtimeType}');
super.onTransition(t);
}
}
String describe(TaskState s) => switch (s) {
TaskInitial() => 'no data',
TaskLoading() => 'loading',
TaskLoaded(:final tasks) => '${tasks.length} tasks',
TaskFailure(:final message) => 'error: $message',
};
Future<void> main() async {
final bloc = TaskBloc();
bloc.add(TasksRequested());
await Future<void>.delayed(const Duration(milliseconds: 50));
bloc.add(TaskAdded('Send the invoice'));
await Future<void>.delayed(const Duration(milliseconds: 50));
print('final state: ${describe(bloc.state)}');
await bloc.close();
}
// Output:
// TasksRequested: TaskInitial -> TaskLoading
// TasksRequested: TaskLoading -> TaskLoaded
// TaskAdded: TaskLoaded -> TaskLoading
// TaskAdded: TaskLoading -> TaskLoaded
// final state: 3 tasks
In the output every line is a complete transition: the event that caused it, the starting state, the
arrival state. That trace comes from the onTransition method, which Bloc calls
on every change; in a real app you log it in a global BlocObserver instead of in each
class. The last line of the output goes through describe, which uses a switch
on a sealed type: the keyword is a feature of the Dart 3 language, not of the package, and
it makes the compiler check that you have handled every case.
String describe(TaskState s) => switch (s) {
TaskInitial() => 'no data',
TaskLoading() => 'loading',
TaskLoaded(:final tasks) => '${tasks.length} tasks',
// TaskFailure() is missing
};
// Output:
// error - The type 'TaskState' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'TaskFailure()'. - non_exhaustive_switch_expression
The message above is the real one from dart analyze when you delete the
TaskFailure branch. It is the reason states are declared sealed: if in six
months you add a state, every switch on the screen stops compiling until you handle it.
The class modifiers documentation confirms it:
with sealed the compiler knows all the direct subtypes and flags non-exhaustive switches.
What really changed in versions 3.0 and 9
Many comparisons out there attribute to the two versions features that come from somewhere else, so it
pays to read the changelogs. For BLoC 9, the bloc package changelog
lists two changes marked BREAKING: the introduction of EmittableStateStreamableSource
(implemented by BlocBase) and the removal of BlocOverrides, already deprecated.
There is no "native support for sealed classes": those come from Dart 3, and work with any recent
version of bloc. For Riverpod 3, the page
What's new in Riverpod 3.0 and the
migration guide describe the novelties that
change runtime behaviour:
- Automatic retries: a provider that fails retries up to 10 times by default, but
ErrorandProviderExceptionare not retried. - Providers paused off screen: the listeners of widgets that are not visible are paused, and you control this with
TickerMode. - Exception on a destroyed
Ref: using aRefafter theawaitonce the provider has been disposed throwsUnmountedRefException; you guard against it withref.mounted. - "Legacy" providers:
StateProvider,StateNotifierProviderandChangeNotifierProviderare imported fromflutter_riverpod/legacy.dart. - Comparison with
==: all providers filter updates with==, and no longer partly withidentical.
The migration page warns that the lifecycle change "may break your app in subtle ways". The first point
is the riskiest in production: a call that used to fail immediately is now repeated up to ten times, and
if that call is not idempotent (a payment, a send) you get duplicated effects. You turn it off for the
whole app, or for a single provider, with the retry parameter:
void main() {
runApp(
ProviderScope(
// Never a new attempt, for any provider
retry: (retryCount, error) => null,
child: const MyApp(),
),
);
}
This block is a pattern to adapt, copied in form from the migration guide: it needs a Flutter project
with MyApp, so I did not run it. The function passed to retry receives the
attempt number and the error and returns how long to wait before retrying; returning null
means "never", which is the right value for operations that modify data.
Code generation: how much it helps and what changes
With riverpod_generator you write an annotation and the package generates the provider.
The article on the Riverpod deep dive
uses it in detail; here one little-known consequence matters. I generated the code with
build_runner in a test project (34 seconds, about 700 MB of memory, measured with
/usr/bin/time -v on this machine) and opened the output file.
@riverpod
String greeting(Ref ref) => 'hello';
@Riverpod(keepAlive: true)
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
}
// Output:
// in the generated file gen.g.dart:
// GreetingProvider -> isAutoDispose: true
// CounterProvider -> isAutoDispose: false
The generated file declares isAutoDispose: true for the plain provider and
isAutoDispose: false for the one with keepAlive: true. The
automatic disposal documentation
confirms it: with the generator it is on by default, without the generator you enable it with
isAutoDispose: true. So the sentence "providers are disposed when they have no more
listeners" is true only for generated providers or those declared with that flag: a hand-written
AsyncNotifierProvider, like ours, stays alive as long as the container exists.
The comparison you can measure
I counted the non-empty lines of the two examples. It is not a productivity benchmark, it is a count of the listings in this article; it depends on how I wrote them.
| Part | Riverpod | BLoC |
|---|---|---|
| State, logic and provider | 14 lines (riverpod_tasks.dart, 23-38) | 40 lines (bloc_tasks.dart, 3-54) |
| Data access | 16 lines of repository, separate | included in the 40, as an in-memory archive |
| Transition tracing | to be written (listen) | 4 lines in onTransition, already in the 40 |
| Error handling | AsyncValue provides it | a TaskFailure state to declare |
Once you level the items (14 plus 16 of repository against 40) the gap shrinks to about ten lines, and
the real difference is another one: in Riverpod the state type is already there (AsyncValue),
in BLoC you design it yourself, with the advantage of being able to have domain states such as "draft"
or "under review" instead of forcing everything into the loading-data-error trio.
How to choose in your project
Do not add up the criteria below as points: rank them by how much they weigh in your case, and the first one that turns out to be decisive closes the discussion. The source that acknowledges the plurality of choices is the official Flutter page on state management options, which lists Provider, Riverpod and Bloc among the possibilities without indicating one as mandatory.
- Lots of shared, derived asynchronous data across screens: Riverpod, because the dependency between providers is its model.
- Flows with rules about time (debounce, one operation at a time): BLoC, because every handler accepts an
EventTransformer. - Large team with rigid conventions: BLoC, because events and states impose the same structure on everyone.
- Small team, prototype that must grow: Riverpod, because it takes fewer files to start.
- Codebase already written in one of the two: stay where you are, unless there is a measurable reason.
The second criterion has a precise source: the Bloc concepts guide
explains that the advantage of Bloc over Cubit lies in reactive operators such as
debounceTime and throttle, applied with an EventTransformer, and
recommends starting with Cubit if you are not sure, moving to Bloc when needed.
So there is no obligation to write events from day one.
Migrating from Provider to Riverpod
For anyone with an app built on the provider package, the official guide
Provider vs Riverpod describes the
main differences: providers are no longer widgets but global final variables, you need a
ProviderScope above the app, and the read code moves from BuildContext to
WidgetRef. In the Riverpod documentation I found no command that converts the code: the
riverpod_cli package mentioned in some guides is a command-line tool stuck at version
1.0.3 from 2021, not a migrator. The migration is done by hand, one provider at a time.
What you can do now
You can choose between the two libraries starting from the problem and not from fashion, you can write
the same feature in both and read its trace, and you know which Riverpod 3 novelties can surprise you in
production: automatic retries, paused listeners, the exception on Ref. The next step is
Riverpod in depth or
BLoC in depth, depending on the road
you chose; to check the behaviour you then have
widget testing.
Sources
- What's new in Riverpod 3.0 - list of the 3.0 novelties, accessed 2026-11-12
- Migrating from 2.0 to 3.0 - automatic retries (10 by default), provider pausing,
UnmountedRefException, legacy imports, comparison with==, accessed 2026-11-12 - Automatic disposal - automatic disposal on by default only with code generation, accessed 2026-11-12
- Provider vs Riverpod - differences in how providers are defined and read, accessed 2026-11-12
- bloc package changelog - the two BREAKING changes of 9.0.0, accessed 2026-11-12
- Bloc Concepts - Cubit, Bloc,
EventTransformer, accessed 2026-11-12 - Class modifiers -
sealedand exhaustive switches, accessed 2026-11-12 - List of state management approaches - the options listed by the Flutter documentation, accessed 2026-11-12
- riverpod_cli on pub.dev - version 1.0.3 published 2021-12-04, accessed 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment