Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you update the state of a riverpod Future provider via a method

I have a futureProvider that watching the stream of AuthStateChanges and adjusts its state accordingly, but I also want to be able to manually control the state but I can use a method because its telling me the type if future, I have also tried using a Future method with async and it still doesn’t work. so how do you use methods to control the state of a FutureProvider?

enum LoginTypes {
  NotSignedIn,
  Anonymous,
  AppleNoEmail,
  LoggedInEmail,
}

@riverpod
class LoginType extends _$LoginType {
  @override
  Future<LoginTypes> build() async {
    final userAuthState = ref.watch(userAuthProvider);
    print('Stream being called from loginType');

    return userAuthState.when(
      data: (user) async {
        if (user == null) {
          return LoginTypes.NotSignedIn;
        } else {
          try {
            // Access the Firestore collection for users
            CollectionReference userCollection =
                FirebaseFirestore.instance.collection('users');

            // Retrieve the document with the given UID
            DocumentSnapshot userDocument =
                await userCollection.doc(user.uid).get();

            // Check if the document exists
            if (userDocument.exists) {
              // Retrieve and return the user's email
              String? userEmail = userDocument.get('email') as String?;
              print(userEmail);

              if (userEmail == 'anom@gmail.com') {
                return LoginTypes.Anonymous;
              } else if (userEmail == 'apple@gmail.com') {
                return LoginTypes.AppleNoEmail;
              } else {
                return LoginTypes.LoggedInEmail;
              }
            }

            return LoginTypes.NotSignedIn;
          } catch (e) {
            print('Error checking user type: $e');
            return LoginTypes.NotSignedIn;
          }
        }
      },
      loading: () => LoginTypes.NotSignedIn,
      error: (_, __) => LoginTypes.NotSignedIn,
    );
  }

  void setToEmail() {
    state = LoginTypes.LoggedInEmail;
  }

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can wrap the value with AsyncData.

void setToEmail() {
  state = AsyncData(LoginTypes.LoggedInEmail);
}

See:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading