Search code examples
flutterdartfuture

How to extract the return value from THEN in flutter?


I want to return one single user from two different user collections inside Stream function. Now, I need to extract the value comes from .then((value) => ... ), so I can return it. In the code below, always return null because I can not use the value inside then outside then.

  Stream? getCurrentUser(String uid) {
    final adminRef = firebaseFirestore!.collection(FirebaseConst.admins).doc(uid).get();
    adminRef.then((value){
      if(value.exists){
        final adminsCollection = firebaseFirestore!.collection(FirebaseConst.admins).where("uid", isEqualTo: uid).limit(1);
        return adminsCollection.snapshots().map((querySnapshot) => querySnapshot.docs.map((e) => AdminrModel.fromSnapshot(e)).toList().first);
      }else if (!value.exists){
        final usersCollection = firebaseFirestore!.collection(FirebaseConst.users).where("uid", isEqualTo: uid).limit(1);
        return usersCollection.snapshots().map((querySnapshot) => querySnapshot.docs.map((e) => UserModel.fromSnapshot(e)).toList().first);
      }
    });
    return null;
  }

I tried to use async/await but it doesn’t work with Streams.


Solution

  • I just solve the problem by using async* and yield* @Richard Heap

    Stream? getCurrentUser(String uid) async* {
        final adminRef = await firebaseFirestore!.collection(FirebaseConst.admins).doc(uid).get();
        if(adminRef.exists){
              final adminsCollection = firebaseFirestore!.collection(FirebaseConst.admins).where("uid", isEqualTo: uid).limit(1);
              yield* adminsCollection.snapshots().map((querySnapshot) => querySnapshot.docs.map((e) => AdminModel.fromSnapshot(e)).toList().first);
        }
            final usersCollection = firebaseFirestore!.collection(FirebaseConst.users).where("uid", isEqualTo: uid).limit(1);
            yield* usersCollection.snapshots().map((querySnapshot) => querySnapshot.docs.map((e) => UserModel.fromSnapshot(e)).toList().first);
    }