Saltar al contenido principal

Logging and error reporting

Riverpod natively offers a way to listen to all events happening in the provider tree.
This can be used to log all the events or to report errors to a remote service.

This is achieved by using the ProviderObserver class, and passing it to ProviderScope/ProviderContainer.

Defining a ProviderObserver

A ProviderObserver is a class that should be extended.
It offers various methods which can be overridden to listen to events:

  • didAddProvider, called when a provider is added to the tree
  • didUpdateProvider, called when a provider is updated
  • didDisposeProvider, called when a provider is disposed
  • providerDidFail, when a synchronous provider throws an error
class MyObserver extends ProviderObserver {

void didAddProvider(
ProviderBase<Object?> provider,
Object? value,
ProviderContainer container,
) {
print('Provider $provider was initialized with $value');
}


void didDisposeProvider(
ProviderBase<Object?> provider,
ProviderContainer container,
) {
print('Provider $provider was disposed');
}


void didUpdateProvider(
ProviderBase<Object?> provider,
Object? previousValue,
Object? newValue,
ProviderContainer container,
) {
print('Provider $provider updated from $previousValue to $newValue');
}


void providerDidFail(
ProviderBase<Object?> provider,
Object error,
StackTrace stackTrace,
ProviderContainer container,
) {
print('Provider $provider threw $error at $stackTrace');
}
}

Using a ProviderObserver

Now that we've defined an observer, we need to use it.
To do so, we should pass it to either ProviderScope or ProviderContainer:

runApp(
ProviderScope(
observers: [
MyObserver(),
],
child: MyApp(),
)
);
final container = ProviderContainer(
observers: [
MyObserver(),
],
);