I'm using Riverpod in Flutter, and recently I've been migrating from StateNotifierProvider to NotifierProvider. As part of the migration, I made modifications to the Riverpod code that monitors the app's lifecycle and automatically changes the Flutter app's theme when the appearance mode of the app changes. I have a question regarding this modification.
Before the modification:
final sampleProvider =
StateNotifierProvider<SampleNotifier, SampleState>((ref) {
final observer = SampleNotifier();
final binding = WidgetsBinding.instance..addObserver(observer);
ref.onDispose(() {
binding.removeObserver(observer);
});
return observer;
});
After the modification:
final sampleProvider =
NotifierProvider.autoDispose<SampleNotifier, SampleState>(() {
final observer = SampleNotifier();
WidgetsBinding.instance.addObserver(observer);
//final binding = WidgetsBinding.instance..addObserver(observer);
// ref.onDispose(() {
// binding.removeObserver(observer);
// });
return observer;
});
In this modification from StateNotifierProvider to NotifierProvider, I removed the following part:
ref.onDispose(() {
binding.removeObserver(observer);
});
Is it okay to remove this part? Will it have any negative impact or cause inefficiency in the app if the observer keeps getting bound indefinitely?
It seems like you removed the disposal logic since you do not have access to the ref
object.
In the new Notifier
class, you can handle the initialisation and disposal logic inside the build method of SampleNotifier
.
class SampleNotifier extends Notifier<SampleState> with WidgetsBindingObserver{
@override
SampleState build() {
final binding = WidgetsBinding.instance..addObserver(this);
ref.onDispose(() {
binding.removeObserver(this);
});
return ...;
}
}