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 treedidUpdateProvider
, called when a provider is updateddidDisposeProvider
, called when a provider is disposedproviderDidFail
, 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(),
],
);