简体   繁体   中英

Using Riverpod in Flutter to implement session user data management

I am using Riverpod in Flutter to handle Firebase authentication, and it seems to be working fine. Additionally, I'd like to use Riverpod to handle core user data (ie "session" data). The problem is that if a user logs out and another logs in, the user session data is not fetched/refreshed for that new user.

Authentication (and the semi-working session data handling) is handled the following way:

return authState.when(
    data: (authData) {
      if (authData != null) {

        // Get user data here:
        final userState = ref.watch(appUserProvider);

        return userState.when(
            data: (appUser) {
              if (appUser.isFirstRun) {
                return const OnboardingPage();
              } else {
                return const AppRoot();
              }
            },
            loading: () => const LoadingScreen(),
            error: (e, stackTrace) => ErrorDisplay(e, stackTrace));
      }
      return const LoginPage();
    },
    loading: () => const LoadingScreen(),
    error: (e, stackTrace) => ErrorScreen(e, stackTrace));

As seen above, I'd like the appUserProvider to be provided once the auth state has been provided, but am having trouble getting this nested approach to work properly. When one user logs out and another logs in, the data is not automatically refreshed without an app restart. Trying to refresh the appUserProvider explicitly (using ref.read()) does not work either.

The appUserProvider looks like this:

   final appUserProvider = StateNotifierProvider<AppUserNotifier, AsyncValue<AppUser>>((ref) {
      return AppUserNotifier(ref);
    });
        
    class AppUserNotifier extends StateNotifier<AsyncValue<AppUser>> {
      final StateNotifierProviderRef ref;
        
      late final UserService service;
        
      AppUserNotifier(this.ref) : super(AsyncValue.data(AppUser())) {
        service = ref.watch(userService);
        get();
    } 
// get method omitted

How can I get this to work properly? Is it even a good approach?

Thankful for any input here!

You can use this for your StateNotifierProvider:

final appUserProvider = StateNotifierProvider.autoDispose<AppUserNotifier, AsyncValue<AppUser>>((ref) {
      return AppUserNotifier(ref);
    });

Then the provider will be disposed of as soon as it is no longer used. When a new user logs in, the provider is initialized again with the correct data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM