Sub topic 13
Provider Lifecycle and `autoDispose`
Assume you know Dart classes, generics, Future, and async/await. You should also understand ConsumerWidget, ref.watch, and basic Riverpod providers.
A provider owns a value and keeps that value in a provider container. The value remains available while the provider has listeners. A listener is usually a widget that calls ref.watch.
An ordinary provider can keep its state for the lifetime of the container. An autoDispose provider has a shorter lifetime. Riverpod destroys its state when no listener remains. This prevents temporary screens and parameterized requests from filling memory indefinitely.
Choosing between persistent and disposable state
Use a normal provider when the value should stay available for the container's lifetime. Examples include configuration, a repository, or an authentication session.
Use autoDispose when the value belongs to a screen, request, route, or parameter. Riverpod normally disposes the state after it has no listeners for a frame. If another widget starts listening before disposal, the existing state can remain available.
| Provider declaration | Typical lifetime |
|---|---|
| `FutureProvider<User>` | Until the container is disposed |
| `FutureProvider.autoDispose<User>` | While it has listeners |
| `FutureProvider.autoDispose.family<User, int>` | While listeners use that specific user ID |
Disposing a parameterized provider
A family creates a separate provider instance for each argument. Combining family with autoDispose is useful for detail pages because each ID gets independent state.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final userNameProvider =
FutureProvider.autoDispose.family<String, int>((ref, userId) async {
ref.onDispose(() {
// Cancel or release resources associated with this request.
});
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $userId';
});A widget can listen to one instance:
class UserName extends ConsumerWidget {
const UserName({super.key, required this.userId});
final int userId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final result = ref.watch(userNameProvider(userId));
return result.when(
data: Text.new,
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
);
}
}ref.onDispose registers cleanup code. Use it for timers, stream subscriptions, controllers, and cancellation tokens. Cleanup should be synchronous and should not modify another provider.
Keeping successful state alive
Sometimes a request should be disposable while loading but remain cached after it succeeds. Call ref.keepAlive() after the successful work finishes.
final articleProvider =
FutureProvider.autoDispose.family<String, int>((ref, articleId) async {
final article = await fetchArticle(articleId);
ref.keepAlive();
return article;
});
Future<String> fetchArticle(int id) async => 'Article $id';Use keepAlive deliberately. Keeping every family instance alive can recreate the memory problem that autoDispose was intended to solve.
Exercise
A search-results provider receives a changing query and should not retain old results forever. Which declaration is appropriate?
Show answer
Use an autoDispose.family provider keyed by the query, and release any request or stream resources with ref.onDispose.