Home > database >  Flutter Firestore - get only 10 docs with their id
Flutter Firestore - get only 10 docs with their id

Time:02-17

here I'm trying to get the top 10 names only from my firebase firestore, and I searched on how I do it with the listview that I have, but I get to nowhere. so I thought about getting the id of my documents instead. In my firestore I gave the top 10 documents IDs from 1 to 10, now I'm stuck and I have no idea how to do it. please help.

static int id = 1;
StreamBuilder<QuerySnapshot>(
      stream: fireStore.collection(path).snapshots(),
      builder: (context, snapshot) {
        if(!snapshot.hasData){
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.blueAccent,
            ),
          );
        }
        List<InfoBox> ancients = [];
        try {
          final collection = snapshot.data!.docs;
          for (var collect in collection) {
            final name = collect['Name'];
            final image = collect['Image'];
            final collectionWidget = InfoBox(
                ancientName: name,
                ancientImage: image
            );
            ancients.add(collectionWidget);
          }
        }catch(e){
          print('problems in stream builder \n error : $e');
        }
        return Expanded(
            child:ListView(
              children: ancients,
            )
        );
      },
    );

CodePudding user response:

You are probably searching for limit() function. According to the documentation:

To limit the number of documents returned from a query, use the limit method on a collection reference

You can implement it like this:

fireStore.collection(path).limit(10).snapshots();

CodePudding user response:

Change your ListView to this List if else everything is ok and u are getting data in list then this will work.

ListView.builder(
  itemCount: ancients.length,
  itemBuilder: (BuildContext context, int index) {

    return ListTile(
    leading: new Image.network(ancients[index].ancientImage),
  title: new Text(ancients[index].ancientName),
    )
  },
  )
  • Related