Solved: How to Retrieve data from firebase firestore using the UserID in flutter?

Question

Asked by Shehan L on December 23, 2021 (source).

I want to retrieve the userName from firebase firestore per each user logins. So i wan't to retreive user data using the userID from firebase and display it.

I have attached my current code below.

How can i adjust the below code to get the userName from firestore using the user_ID as the primary key?

Current code :

class GetUserName extends StatelessWidget {

  final String documentId;

  GetUserName(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data =
              snapshot.data!.data() as Map<String, dynamic>;
          return Text("Hello, ${data['userName']}");
        }

        return Text("loading");
      },
    );
  }
}

Thank you in advance :)

Answer

Question answered by Frank v (source).

You'll want to use a StreamBuilder on `` to deal with the current user, something like this:

return StreamBuilder(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.active) {
      return Center(child: CircularProgressIndicator()); // 👈 user is loading
    }
    final user = snapshot.data;
    final uid = user.uid; // 👈 get the UID
    if (user != null) {
      print(user);

      CollectionReference users = FirebaseFirestore.instance.collection('users');

      return FutureBuilder<DocumentSnapshot>(
        future: users.doc(uid).get(),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.hasError) {
            return Text("Something went wrong");
          }

          if (snapshot.hasData && !snapshot.data!.exists) {
            return Text("Document does not exist");
          }

          if (snapshot.connectionState == ConnectionState.done) {
            Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
            return Text("Hello, ${data['userName']}");
          }

          return Text("loading");
        },
      );
    } else {
      return Text("user is not logged in");
    }
  },

I always keep the FlutterFire documentation handy when doing things like this

DART FIREBASE FLUTTER GOOGLE-CLOUD-FIRESTORE
SHARE: