0
votes

I'm trying to have a StreamProvider provide a 'kaizenUser' object throughout the rest of the app. To get this 'KaizenUser' i've pulled the user from firebase authentication. Then using the uid of the firebase auth user, ive used that to access my own user doc form firebase.firestore to create the KaizenUser with the added 'role' information from my firestore user.

Spent a few days wrestling with the code in auth service and i think i'm so close...

Starting with the StreamProvider:

Widget build(BuildContext context) {
    return StreamProvider<KaizenUser>.value(
      value: AuthService().user,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Wrapper(),
      ),
    );
  }

Auth Service class. The get user stream calls userFromFirebaseUser, in which I call getRole to find the document reference of the equivalent user in firestore and the 'role' field. Then back in userFromFirebaseUser, use that role field to create a complete KaizenUser which will be passed through the stream.

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // auth change user stream
  Stream<KaizenUser> get user async* {
    yield* _auth
        .authStateChanges()
        .map((User user) => _userFromFirebaseUser(user));
  }

  //Create KaizenUser object based on firebase user
  KaizenUser _userFromFirebaseUser(User user) {
    String role = getRole(user.uid) as String;
    KaizenUser kaizenUser =
        KaizenUser(uid: user.uid, email: user.email, role: role);
    return kaizenUser;
  }

  // ignore: missing_return
  Future<String> getRole(String uid) async {
    var doc =
        await FirebaseFirestore.instance.collection('users').doc(uid).get();
    return doc.data()['role'];
  }

The error is: Type Future is not of type String in type cast.

Whilst writing this out im thinking the problem line of code the cast 'as String'

String role = getRole(user.uid) as String;

Any help is greatly appreciated!

1

1 Answers

1
votes

The error is because you are not awaiting for the future result to be returned. Try the following :

String role = await getRole(user.uid):