autoDispose constant

AutoDisposeProviderBuilder const autoDispose

Marks the provider as automatically disposed when no-longer listened.

Some typical use-cases:

  • Combined with StreamProvider, this can be used as a mean to keep the connection with Firebase alive only when truly needed (to reduce costs).
  • Automatically reset a form state when leaving the screen.
  • Automatically retry HTTP requests that failed when the user exit and re-enter the screen.
  • Cancel HTTP requests if the user leaves a screen before the request completed.

Marking a provider with autoDispose also adds an extra property on ref: maintainState.

The maintainState property is a boolean (false by default) that allows the provider to tell Riverpod if the state of the provider should be preserved even if no-longer listened.

A use-case would be to set this flag to true after an HTTP request have completed:

final myProvider = FutureProvider.autoDispose((ref) async {
  final response = await httpClient.get(...);
  ref.maintainState = true;
  return response;
});

This way, if the request failed and the UI leaves the screen then re-enters it, then the request will be performed again. But if the request completed successfully, the state will be preserved and re-entering the screen will not trigger a new request.

It can be combined with ref.onDispose for more advanced behaviors, such as cancelling pending HTTP requests when the user leaves a screen. For example, modifying our previous snippet and using dio, we would have:

final myProvider = FutureProvider.autoDispose((ref) async {
+ final cancelToken = CancelToken();
+ ref.onDispose(() => cancelToken.cancel());

+ final response = await dio.get('path', cancelToken: cancelToken);
- final response = await dio.get('path');
  ref.maintainState = true;
  return response;
});

Implementation

static const autoDispose = AutoDisposeProviderBuilder();