Ashwani Kumar
Ashwani Kumar

Reputation: 234

How add/fetch data from firestore using StreamBuilder<QuerySnapshot> in flutter?

I want to add data in my firestore like

->users(collection)->userid(document)->friends(collection)

I want to add/fetch data from friends collection

Here is my code:

 Future<void> _getUserDoc() async {
    final FirebaseAuth _auth = FirebaseAuth.instance;
    final Firestore _firestore = Firestore.instance;

    FirebaseUser user = await _auth.currentUser();
    DocumentReference ref = _firestore.collection('users').document(user.uid);
 }


Widget _buildBody(BuildContext context) {
  return StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance
        .collection('users')
        .document()
        .collection('friends')
        .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData)
        return Center(
            child: CircularProgressIndicator(
          backgroundColor: Colors.deepPurple,
        ));

      return _buildList(context, snapshot.data.documents);
    },
  );
}

In the widget _buildbody how i use user.uid to fetch the data in friends collection.

Thanks in Advance

Upvotes: 2

Views: 5810

Answers (1)

Ganapat
Ganapat

Reputation: 7508

If your widget is a stateful widget, then you can have user doc reference in state of widget and use same ref for fetching friends collection data like:

 DocumentReference userRef;
 @override
 initState(){ 
  super.initState();
  _getUserDoc();
 } 

 //Call this method from initState()
 Future<void> _getUserDoc() async {
    final FirebaseAuth _auth = FirebaseAuth.instance;
    final Firestore _firestore = Firestore.instance;

    FirebaseUser user = await _auth.currentUser();
    setState((){
      userRef = _firestore.collection('users').document(user.uid);
    });
 }


Widget _buildBody(BuildContext context) {
  if(userRef == null) {
  CircularProgressIndicator(
          backgroundColor: Colors.deepPurple,
        ));
  }

  return StreamBuilder<QuerySnapshot>(
        stream: userRef
        .collection('friends')
        .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData)
        return Center(
            child: CircularProgressIndicator(
          backgroundColor: Colors.deepPurple,
        ));

      return _buildList(context, snapshot.data.documents);
    },
  );
}

P.S. : Just make sure, userRef is not null before calling StreamBuilder function "_buildBody"

Upvotes: 4

Related Questions