user14431894
user14431894

Reputation:

Flutter: Streambuilder for documents from query

How do I get a listview of all the items returned from query snapshot?

FirebaseFirestore.instance
        .collection("children")
        .where("parentUID", isEqualTo: uid)
        .snapshots()
        .listen((result) {
      result.docs.forEach((result) {
        setState(() {
          childFirstName = result["childFirstName"];
          childLastName = result["childLastName"];
          points = result["points"];
          docID = result.id;
          print('$docID');
        });
      });
    });
  }

This is all I could come up with, here is an image of the database,
Image of database

How can I make a listview which creates an item for every document which the parentUID is equal to the current users uid which is already stored in a variable uid

Upvotes: 0

Views: 1613

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7716

You can use the sample code below. It shows how to use the stream from your query and return a ListView.builder which displays the information in a ListTile.

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
  stream: FirebaseFirestore.instance
    .collection('children')
    .where('parentUID', isEqualTo: uid)
    .snapshots(),
  builder: (BuildContext context, snapshot) {
    if (snapshot.data == null) {
      return Center(child: CircularProgressIndicator());
    } else {
      final List<QueryDocumentSnapshot<Map<String, dynamic>>> docs = snapshot.data!.docs;

      return ListView.builder(
        itemCount: docs.length,
        itemBuilder: (_, index) {
          final doc = docs[index];
          final childFirstName = doc["childFirstName"];
          final childLastName = doc["childLastName"];
          final points = doc["points"];
          final docID = doc.id;

          return ListTile(
            title: Text('$childFirstName $childLastName'),
            subtitle: Text(points),
          );
        },
      );
    }
  },
)

Upvotes: 2

Related Questions