In Riverpod, automatic disposal destroys provider resources when they are no longer used.
- Using Code Generation: Automatic disposal is enabled by default. To opt-out (keep the state alive), set
keepAlive: true in the @Riverpod annotation. - Without Code Generation: You must explicitly opt-in by setting
isAutoDispose: true when creating the provider.
Caution: It is highly recommended to enable automatic disposal for providers that receive parameters (families) to prevent memory leaks caused by accumulating state for every parameter combination.
// Disable automatic disposal using code-generation
@Riverpod(keepAlive: true)
String helloWorld(Ref ref) => 'Hello world!';
// Opt-in to automatic disposal without code-generation
final helloWorldProvider = Provider<String>(
isAutoDispose: true,
(ref) => 'Hello world!',
);