Search code examples
flutterriverpodflutter-riverpod

Riverpod provider with fetch-once async call


I am using Riverpod 2 provider to get value from a Future Provider as shown below.

@riverpod
Future<AppUser> fetchCurrentUser(FetchCurrentUserRef ref) async {
  // usersRef is the Firebase ODM refence here
  final ref = await usersRef.doc(FirebaseAuth.instance.currentUser!.uid).get();
  return ref.data!;
}

I use the above provider using ref.watch(fetchCurrentUserProvider).when() to display in the UI. It all works fine.

I understand that the values will be cached for next time use.

What I am looking for is to avoid the async when() everytime when consuming it. How can I make the initial future call to happen only once so that I can use the ref without worrying about the async nature.

Still, I want to use Riverpod for state management, but avoid dealing with loading, error and when actions of a future provider.

Whenever I want to use it, I will be getting the value directly, somehting like ref.watch(fetchCurrentUserProvider).avatar_url.


Solution

  • Having to use when everywhere is not something you should fight. Everywhere you uses the result, there's a change it's in loading or error state. So you should handle those

    If you're absolutely certain your future is resolved, you can do ref.watch(provider).requireValue.whatever