How do I call a method on an 'auto disposing' Notifier before the first watcher registers? #3182
Replies: 1 comment
-
I've ran into a similar problem. The way I solved it was by doing this where you make the navigation: final subscription = ref.listenManual(provider, (_, __) {});
try {
ref.read(provider.notifier).start();
Navigator.push(context, ...);
} finally {
WidgetsBinding.instance.addPostFrameCallback((_) {
subscription.close();
});
} It will create the provider instance when you call Also, if your navigation redirects you for some reason, then the subscription will close after the next frame which will dispose the provider. So worst case, your provider takes up memory for an extra frame. |
Beta Was this translation helpful? Give feedback.
-
I have an
AutoDisposeNotifier
and a correspondingNotifierProvider.autoDispose<...>
. The notifier has a method, let's call itstart
, that triggers execution of the logic.In my use case, the users clicks a button and another route is pushed, with a widget that
watch
es the provider. I would like thestart
method to be called automatically, before this widget is first drawn, and I have some kind of a mental block and I don't know how to do it. I tried various things:ref.read(provider.notifier).start()
right before navigation - this however initializes the notifier, callsstart
, and then immediately disposes it. The reason is that there are no listeners and the provider is 'auto disposing' (and I need it to stay this way).ConsumerStatefulWidget
and tried callingref.read(provider.notifier).start()
ininitState
- this fails an assertion that I'm changing the notifier in a widget lifecycle.WidgetsBinding.instance.addPostFrameCallback(...)
ininitState
, and calledref.read(provider.notifier).start()
in the callback - this actually works, but the UI flickers initially because the widget is first drawn with the initial state (beforestart
) and then almost immediately is redrawn with the new state (afterstart
). The same happens when I use aFuture(() => ...)
ininitState
. This is not the UX I want.All works fine apart from that, when I trigger
start
using a button or something like this. But how do I trigger it without a button?Beta Was this translation helpful? Give feedback.
All reactions