Flutter: Firestore Get User uid inside StreamBuilder

1,460

Getting the UID is an asynchronous operation, so requires a FutureBuilder.

If you want to use the UID to then build a stream, you'll need to have a FutureBuilder for the UID, and then inside of that a StreamBuilder for the stream from the database.

body: FutureBuilder(
  future: FirebaseAuth.instance.currentUser(),
  builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
    if (snapshot.hasData) {
      return StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection(snapshot.data.uid).snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapShot){
          ...
        },
      )
    }
    else {
      return Text('Loading user data...');
    }
Share:
1,460
Alex Ali
Author by

Alex Ali

Updated on December 21, 2022

Comments

  • Alex Ali
    Alex Ali 3 minutes

    I have an app which I want to display documents inside collection.. the collection reference is the uid of the user.

    Is there a way to get current user uid and put this uid inside StreamBuilder in stream.

    I have tried like so but it did not work and returned null:

    class _MyAdsState extends State<MyAds> {
     final FirebaseAuth _auth = FirebaseAuth.instance;
    Future getCurrentUser() async {
     final FirebaseUser user = await _auth.currentUser();
     final uid = user.uid;
     print(uid);
     return uid.toString();
    }
    @override
      Widget build(BuildContext context) {
       return Scaffold(
    body: Column(
     Expanded(
              child: StreamBuilder<QuerySnapshot>(
                stream: Firestore.instance.collection("${getCurrentUser()}").snapshots(),
                builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapShot){
                  if(querySnapShot.hasError){
                    return Text('Some Error');
                  }
                  if(querySnapShot.connectionState == ConnectionState.waiting){
                    return CircularProgressIndicator();
                  }else{
                    final list = querySnapShot.data.documents;
                    return ListView.builder(
                        itemBuilder: (context, index){
                          return ListTile(
                            title: Text(list[index]["subject"]),
                            subtitle: Text(list[index]["category"]),
                          );
                        },
                      itemCount: list.length,
                    );
                  }
                },
              )