iTranslated by AI
Migration Guide to Riverpod 3 in Flutter
Introduction
Riverpod 3.0 was officially released on September 10, 2025.
While this update brought many conveniences, writing code with the same mindset as 2.x can lead to unexpected pitfalls.
I've compiled a list of things to watch out for when migrating from the 2.x series to the 3.x series as someone who used the 2.x series.
I hope this article helps those who are about to upgrade to the 3.x series of Riverpod.
Target Audience
- Flutter/Dart developers migrating from Riverpod 2.x to 3.x
- Those who want to understand changes in AsyncValue / Notifier / Provider lifecycle
- Those who want to avoid new specifications and pitfalls related to Stream/async providers
- Those who need to adapt to new retry/override behavior in tests
Author's Environment at Time of Writing
[✓] Flutter (Channel stable, 3.35.4, on macOS 26.0.1 25A362 darwin-arm64, locale ja-JP)
[✓] Xcode - develop for iOS and macOS (Xcode 16.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.2)
[✓] VS Code (version 1.104.3)
[✓] Connected device (5 available)
[✓] Network resources
dependencies:
flutter:
sdk: flutter
hooks_riverpod: 3.0.3
flutter_hooks: ^0.21.0
riverpod_annotation: 3.0.3
dev_dependencies:
flutter_test:
sdk: flutter
riverpod_generator: 3.0.3
build_runner: ^2.4.8
custom_lint: ^0.8.0
riverpod_lint: 3.0.3
Features Not Covered in This Article
Many features were introduced in this update.
Among the major ones, the following two features are not covered here:
- Offline persistence
- Mutations
I will omit detailed explanations of each feature, but in addition to being completely new, they are still considered experimental by the official docs.
While they are very useful, I think it's better to carefully verify and consider before incorporating them into a product.
Implementation Migration
Consolidation of valueOrNull and value
For AsyncValue, there was a getter called valueOrNull that returns the value if present, or null if loading or in an error state, without using switch or when.
There was also another getter called value, which was basically the same as valueOrNull, with the only difference being that it would throw an exception if there was an error on the first fetch.
However, this time, the behavior is that of valueOrNull, but the naming now uses value. In other words, the old value has been removed.
It's a bit confusing, but to summarize:
| State | Return Value |
|---|---|
| Initial loading | null |
| Error on first attempt | null |
| Loading on second attempt or later | Previous value |
| Error on second attempt or later | Previous value |
| Data fetched successfully | New value |
In practice, search and replace occurrences of valueOrNull with the appropriate replacement.
// Writing style in Riverpod 2.x
final asyncUserName = ref.watch(userNameProvider);
final user = asyncUserName.valueOrNull ?? 'Unknown'; // may be null
// Writing style in Riverpod 3.x
final asyncUserName = ref.watch(userNameProvider);
final user = asyncUserName.value ?? 'Unknown'; // may be null
I hadn't been using .value before, so simply replacing was fine for me, but if you were intentionally using .value and accounting for initial errors, be aware that the behavior changes.
Removal of Ref Subclasses
This change was technically introduced in Riverpod 2.6.0, but it's listed in the official 3.0 migration guide, so I'll mention it.
When declaring a provider, the Ref name you used to write as a subclass like XxxRef can now just be Ref.
This will generate many warnings when updating, so simply replace them.
// ===== Before (Riverpod 2.x) =====
@riverpod
Future<User> fetchUser(FetchUserRef ref) async {
// ...
}
// ===== After (Riverpod 3.x) =====
@riverpod
Future<User> fetchUser(Ref ref) async {
// ...
}
Retry Configuration
Previously, if a provider failed to be created, it was immediately treated as an error.
Starting from 3.0, retries are performed by default when an error occurs.
The retry interval starts with a delay of 200 milliseconds, doubling with each retry up to a maximum of 6.4 seconds. The number of retries is set to 10.
You can customize this behavior in the ProviderScope directly under the main function.
void main() {
runApp(
ProviderScope(
// You can customize the retry logic, such as to skip
// specific errors or add a limit to the number of retries
// or change the delay
retry: (retryCount, error) {
if (error is SomeSpecificError) return null;
if (retryCount > 5) return null;
return Duration(seconds: retryCount * 2);
},
child: MyApp(),
),
);
}
The above applies to all providers, but you can also set individual configurations per provider.
Duration retry(int retryCount, Object error) {
if (error is SomeSpecificError) return null;
if (retryCount > 5) return null;
return Duration(seconds: retryCount * 2);
}
@Riverpod(retry: retry)
class TodoList extends _$TodoList {
@override
List<Todo> build() => [];
}
This feature is expected to be used, for example, for retrying when an API call fails inside a provider.
However, in my case, I didn't need this setting, so I disabled it as follows:
runApp(
ProviderScope(
// disable retry
retry: (_, __) => null,
// ....
),
);
Note that this retry mechanism also applies in tests.
In tests, you need to define a ProviderScope per test file, so be careful.
Details will be discussed later.
Provider Lifecycle Changes
Apart from the new features, the major change in this update is the Provider lifecycle changes.
The rough overview is:
- Providers are paused when they are no longer visible (controllable)
- When a provider is rebuilt, its subscriptions are paused until the rebuild completes
- When a provider is paused, all its subscriptions are also paused
- Listeners subscribed via
ref.listencan be manually paused and resumed
Looking at this alone, it seems convenient because resources are created only when needed and paused when not. However, in my case, it stopped working properly in the following situations.
Pattern 1: ViewModel
From version 3, the following code does nothing when the button is tapped.
// ViewModel
@riverpod
class SampleViewModel extends _$SampleViewModel {
@override
void build() {}
// Method that makes some changes
Future<void> updateData() async {
// processing contents
}
}
// Screen
class SampleScreen extends HookConsumerWidget {
const SampleScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () async {
// Get instance of ViewModel
final viewModel = ref.read(sampleViewModelProvider.notifier);
await viewModel.updateData();
},
child: const Text('Update'),
),
),
);
}
}
The reason is that there is no instance of the ViewModel at the moment it is read.
Riverpod's author, Remi, explains this as "nobody is listening to this provider."
In other words, since nothing is watching/listening to this provider, it is in a paused state.
There are two solutions for this:
Change read to watch
By watching inside build, you are "listening" and the instance becomes accessible.
// Screen
@override
Widget build(BuildContext context, WidgetRef ref) {
// First, watch
final viewModel = ref.watch(sampleViewModelProvider.notifier);
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () async {
await viewModel.updateData();
},
child: const Text('Update'),
),
),
);
}
Set keepAlive to true
If you set the target provider to not be automatically disposed once created, read will work fine.
The logic is that since the provider is keepAlive, it always exists when you try to read it.
@Riverpod(keepAlive: true)
class SampleViewModel extends _$SampleViewModel {
// ...
}
Pattern 2: Handling await ref.read(provider.future)
Suppose you have a Future/Stream provider.
// Async provider to get settings
@riverpod
Future<bool> isEnabled(Ref ref) async {
// Assume repository is set with keepAlive: true
final repository = ref.read(someRepositoryProvider);
final isEnabled = await repository.get();
return isEnabled;
}
There are cases where you only want the value at the current moment in some method or ViewModel build.
In this case, you would use read instead of watch, and since the value is still an AsyncValue, you'd need to use .future like below:
Future<void> doSomething() async {
// Get the value at this moment
final isEnabled = await ref.read(isEnabledProvider.future);
if (isEnabled) {
// ...
}
}
However, this method no longer works in Riverpod 3.x.
The reason is the same as before: it's not being watched, so it's paused, and on top of that, async-related providers seem to be unreadable even if you set KeepAlive: true.
Remi has mentioned this on the Riverpod GitHub.
Remi doesn't really approve of getting values with await ref.read(provider.future), and it seems that this update adjusted it, causing it to stop working.
The solution Remi proposes is as follows:
final sub = ref.listen(provider.future, (p, n){});
try {
await sub.read();
} finally {
sub.close();
}
In other words, listen, read, and finally close the subscription. But writing this every time is tedious, so I created the following extension and use it.
extension ReadAsyncOnce on MutationTarget {
/// Fetch the "current value" of the target AsyncProvider only once.
/// No recalculation, just subscribe -> get -> close immediately.
/// Equivalent to `await ref.read(provider.future)` in Riverpod 2.x.
Future<T> readAsync<T>(AsyncProviderListenable<T> provider) async {
// Temporarily subscribe to the future provider
final subscription = container.listen(provider.future, (_, __) {});
try {
// If already completed, get immediately; if not, wait for completion
return await subscription.read();
} finally {
subscription.close();
}
}
}
Using it with the earlier example:
Future<void> doSomething() async {
// Get the value at this moment
final isEnabled = await ref.readAsync(isEnabledProvider);
if (isEnabled) {
// ...
}
}
StreamProvider Changes
There are also several significant changes in this area.
The rough summary:
- Providers no longer notify when the same value is emitted via Stream
- You can customize when notifications are sent
- Streaming large data may impact performance
Additionally, although not mentioned in the documentation, providers returning Stream<void> are no longer supported.
Remi has mentioned for a while that he doesn't recommend Stream<void>, so this seems to be the official response.
Therefore, I took the following actions:
Change void-returning streams to bool and use a Notifier that detects changes even for the same value
For example, change a Stream that notifies completion of an API call from void to bool.
class APIService {
APIService(this.ref);
final Ref ref;
/// Stream to notify sync progress
/// Changed from void to bool
final _onCompleted = StreamController<bool>.broadcast();
/// Stream that fires when sync completes
/// Changed from void to bool
Stream<bool> get onCompleted => _onCompleted.stream;
Future<void> fetch() async {
// various communication processes
// Notify completion
// Changed from void to bool
_onCompleted.add(true);
}
}
Previously, a provider that monitors this completion would be written like this:
@riverpod
Stream<void> onCompleted(Ref ref) {
final service = ref.read(apiServiceProvider);
return service.onCompleted;
}
From version 3.x onwards, change it to a Notifier:
@riverpod(name: 'onCompletedNotifier')
class OnCompletedNotifier extends _$OnCompletedNotifier {
@override
Stream<bool> build() {
final service = ref.read(apiServiceProvider);
return service.onCompleted;
}
@override
bool updateShouldNotify(
AsyncValue<bool> previous,
AsyncValue<bool> next,
) {
// Don't notify during error or loading
if (next.hasError || next.isLoading) return false;
// Always send true, so don't compare values; always notify on event
return true;
}
}
Key points:
- Don't use void; always return a value
- Use a Notifier
- Override
updateShouldNotifyto customize notifications
Since we only need to notify completion, I used bool, but String, int, etc. would also work.
Also, to ensure notifications even when the same value is emitted again, I used a Notifier and overrode updateShouldNotify. If you don't need notifications when the value is the same, the traditional Provider style is fine.
Avoid returning objects or list from Stream
I've often felt that Riverpod and Stream don't work well together.
For example, when using async* to perform asynchronous operations inside a method and then return a Stream, comparing previous and next values can fail, or in some cases, cause infinite instance proliferation.
Infinite instance proliferation occurred when using the await for syntax, so avoiding it helps.
In any case, the official documentation also mentions concerns about performance degradation when streaming objects via Stream.
As a conclusion, I decided to adopt the following policy:
- Stream is dedicated to "event notification"
- Actual value retrieval is done via Repository (or similar methods)
- Create a "value-fetching provider" that monitors an internal "change-detection provider"
With this policy,
the "responsibility for change detection" and the "responsibility for value retrieval" are separated,
and it also works well with Riverpod 3's lifecycle changes.
I'll show a concrete example.
The local database Isar has a mechanism to detect changes in the database and emit the changed objects.
Directly using that would look like this:
class UserRepository {
UserRepository(this.ref);
final Ref ref;
/// Get a single stream
Stream<User?> watchOne(String id) async* {
final isar = await ref.read(isarProvider.future);
// Query to find User matching id
final query = isar.userEntitys
.filter()
.isarIdEqualTo(fastHash(id));
// Monitor the data and emit immediately when a change occurs
// watchLazy returns Stream<UserEntity>
// Convert it to domain (User) and emit
// * toDomain implementation is omitted
yield* query
.watchLazy(fireImmediately: true)
.asyncMap((_) async => (await query.findFirst())?.toDomain());
}
}
// Provider to monitor and retrieve a single user's data
@riverpod
Stream<UserData?> userData(Ref ref, String id) =>
ref.read(userRepositoryProvider).watchOne(id);
From now on, I will separate it into one that just emits changes and one that fetches the value.
First, create a class that only monitors changes and a Notifier that communicates those changes.
class IsarOnChangedManager {
IsarOnChangedManager(this.ref);
final Ref ref;
/// Monitor changes to a single User
Stream<bool> watchUser(String id) async* {
final isar = await ref.readAsync(isarProvider);
// watchObjectLazy returns Stream<void>, so replace with bool
yield* isar.userEntitys
.watchObjectLazy(
fastHash(id),
fireImmediately: true,
)
.map((_) => true);
}
}
@Riverpod(keepAlive: true)
IsarOnChangedManager isarOnChangedManager(Ref ref) => IsarOnChangedManager(ref);
@Riverpod(name: 'userOnChangedNotifier')
class UserOnChangedNotifier extends _$UserOnChangedNotifier {
@override
Stream<bool> build(String id) =>
ref.read(isarOnChangedManagerProvider).watchUser(id);
@override
bool updateShouldNotify(
AsyncValue<bool> previous,
AsyncValue<bool> next,
) {
if (next.hasError || next.isLoading) return false;
// Always notify
return true;
}
}
Next, define a method in the repository that simply retrieves a single object.
/// Fetch single entity
Future<User?> findById(String id) async {
final isar = await ref.readAsync(isarProvider);
final entity = await isar.userEntitys.get(fastHash(id));
return entity?.toDomain();
}
Finally, within a Provider, combine the change-notifying provider and the fetch method.
@riverpod
Future<User?> user(Ref ref, String id) async {
// Subscribe to the change-detection Notifier; when a change occurs, this provider will rebuild
ref.watch(userOnChangedNotifier(id));
return ref.read(userRepositoryProvider).findById(id);
}
This may seem like it complicates the implementation, but in a way, separating change detection and retrieval has clarified things.
This point may be controversial, but I hope you find it as one implementation example.
Testing
I'll mainly discuss the new convenient methods added for testing.
ProviderContainer.test
In unit tests, we used to create a ProviderContainer like this:
// Up to Riverpod 2.x
void main() {
late ProviderContainer container;
setUp(() {
container = ProviderContainer();
});
tearDown(() {
container.dispose();
});
}
Writing container.dispose(); every time was cumbersome, so we often wrapped it in a helper function.
Now, a new interface ProviderContainer.test has been introduced.
This interface handles container.dispose(); internally.
Great, no more helper functions needed! But wait, there's the retry issue mentioned earlier.
In tests, if a Provider fails to create, it will retry, so for example, when testing error cases, the default 10 retries will cause a timeout and the test will fail.
Therefore, I ended up creating the following helper function and applying it to all tests:
// Helper function for unit tests on Riverpod 3.x and later
ProviderContainer createContainer({
List<Override> overrides = const [],
List<ProviderObserver> observers = const [],
}) {
return ProviderContainer.test(
overrides: overrides,
observers: observers,
retry: (retryCount, error) => null, // <<<<< THIS SETTING IS NECESSARY!!
);
}
The same issue exists in widget tests, so I also use a helper function like this:
// Helper function for widget tests on Riverpod 3.x and later
ProviderScope createScope({
required Widget child,
List<Override> overrides = const [],
List<ProviderObserver> observers = const [],
}) {
return ProviderScope(
retry: (retryCount, error) => null, // <<<<< THIS SETTING IS NECESSARY!!
overrides: overrides,
observers: observers,
child: child,
);
}
notifierProvider.overrideWithBuild
A dedicated interface has been added to override the initial state of a Notifier.
Mocking Notifiers is discouraged, but you can now override the initial state.
@riverpod(name: 'onCompletedNotifier')
class OnCompletedNotifier extends _$OnCompletedNotifier {
@override
Stream<bool> build() {
final service = ref.read(apiServiceProvider);
return service.onCompleted;
}
}
void main() {
final container = createContainer(
overrides: [
onCompletedNotifier
.overrideWithBuild((_, __) => Stream.value(true)),
],
);
}
Future/StreamProvider Override Restored
This feature existed before and has been restored.
Now you can make fine-grained overrides of AsyncValue.
@riverpod
Future<int> myFutureProvider() async {
return 42;
}
void main() {
final container = ProviderContainer.test(
overrides: [
myFutureProvider.overrideWithValue(AsyncValue.data(42)),
],
);
}
Overriding the Same Provider Multiple Times Now Throws an Error
Previously, code like below would work, but from version 3.x onwards, it properly throws an error.
void main() {
final mockAppSettingRepository = MockAppSettingRepository();
final container = ProviderContainer.test(
overrides: [
appSettingRepositoryProvider.overrideWith((_) => mockAppSettingRepository),
// Overriding the same provider again
appSettingRepositoryProvider.overrideWith((_) => mockAppSettingRepository),
],
);
}
Error log:
Assertion failed: "Tried to override a provider twice within the same container: appSettingRepositoryProvider"
Easier Access to ProviderContainer in Widget Tests
Previously, to access ProviderContainer, you had to write:
// Get BuildContext
final context = tester.element(find.byType(HomeScreen)) as BuildContext;
// Get ProviderContainer
final container = ProviderScope.containerOf(context);
From version 3.x onwards, it's this simple!
final container = tester.container();
Conclusion
Migrating to Riverpod 3.x required a wide range of tasks, from simple replacements like valueOrNull → value, to adapting to Provider lifecycle changes and fundamentally rethinking Stream usage.
Especially the lifecycle changes may be confusing at first, as code that used to work normally suddenly stops working.
However, by understanding countermeasures such as switching to watch, utilizing keepAlive, and introducing the readAsync extension, you can definitely handle it.
Also, for testing, disabling the retry setting is essential, so preparing helper functions will make the migration smoother.
I hope this article serves as a useful reference for those considering migration to Riverpod 3.x.
Let's move forward with stable application development while benefiting from the new features.
Discussion