What's the best way to call an autodispose provider in a function? #1083
Replies: 2 comments 16 replies
-
I'm not a void main() {
runApp(
ProviderScope(
child: MaterialApp(
home: Scaffold(
body: Center(
child: _SomeWidget(),
),
),
),
),
);
}
class _SomeWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = ref.watch(_someProvider);
return TextButton(
onPressed: () {
ref.refresh(_someProvider);
},
child: provider.maybeWhen(
loading: () => const CircularProgressIndicator(),
error: (err, _) => const Text('Error on load!'),
orElse: () => const Text('Continue'),
),
);
}
}
final _someProvider = FutureProvider.autoDispose<void>(
(ref) async {
await Future<void>.delayed(const Duration(seconds: 1));
},
); |
Beta Was this translation helpful? Give feedback.
-
@rrousselGit Do you have any ideas? tl;dr this example https://riverpod.dev/docs/concepts/modifiers/auto_dispose#example-canceling-http-requests-when-no-longer-used goes through the case when you want to start a HTTP request when the user enters a screen, but what if you only want it to start the request when the user has pressed a button? I think this is a valid case if you have a long running HTTP request, maybe uploading a big profile image, and want that request to be cancelled when leaving the screen |
Beta Was this translation helpful? Give feedback.
-
For this example:
I get the following error:
Unhandled Exception: Bad state: The provider AutoDisposeFutureProvider<void>#b5add was disposed before a value was emitted
This error doesn't happen if I remove
loading.value = true;
which i'm guessing is because this line causes a rebuild which triggers the provider to dispose before it attempts to run the rest of the function.If I move all the onPressed logic to a state notifer then I'm not able to use a ref.watch if I pass in ref. If I move the logic to a Provider or change the ref.watch to ref.read then I get the same error above.
Is there a good pattern to follow to get around this while keeping the provider set to autodispose? A working solution I've found involves using a StateProvider or StateNotifierProvider instead of the useState hook to set the loading value but this means multiple providers are being called in the onPressed method which ideally I'd like just one function call per onPressed function call to avoid too much logic in the widget such as
onPressed: () async => ref.read(_someProvider).save()
and thenloading.value
becomesref.watch(_someProvider).isLoading
Beta Was this translation helpful? Give feedback.
All reactions