Milly Alfaro
Milly Alfaro

Reputation: 309

How to order Firestore documents in list form based on int values in flutter

I currently have a list of documents that each contain an int value called plastics. Currently, the list only displays the documents in order by when it was added to the collection, but I want to be able to order the documents based on the int value within each one. I've looked around on the web and I've only found tutorials mostly on ordering timestamps. Is there any documentation or sources on this matter? Here is the code situation I'm working with:

Firstly, in my app users can join groups, and when they do so they bring along their name and int data which is then stored in documents for each user.

Future<String> joinGroup(String groupId, String userUid, String displayName,
      String plastics) async {
    String retVal = 'error';
    List<String> members = List();
    try {
      members.add(displayName);
      await _firestore.collection('Groups').doc(groupId).update({
        'members': FieldValue.arrayUnion(members),
      });
      final uid = FirebaseAuth.instance.currentUser.uid;
      await _firestore.collection('UserNames').doc(uid).update({
        'groupId': groupId,
      });

//Below me is the code for doing so

      await _firestore
          .collection("Groups")
          .doc(groupId)
          .collection("Members")
          .doc(userUid)
          .set({'displayName': displayName, 'plastics': plastics});

      retVal = 'success';
    } catch (e) {}
    return retVal;
  }

I then take that code access the documents and put them in a list.

@override
  Widget build(BuildContext context) {
    final CollectionReference users = firestore.collection('UserNames');

    final String uid = auth.currentUser.uid;

    return FutureBuilder(
        future: users.doc(uid).get(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final result = snapshot.data;
            final groupId = result.data()['groupId'];
            return FutureBuilder<QuerySnapshot>(
                // <2> Pass `Future<QuerySnapshot>` to future
                future: FirebaseFirestore.instance
                    .collection('Groups')
                    .doc(groupId)
                    .collection('Members')
                    .get(), 
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // <3> Retrieve `List<DocumentSnapshot>` from snapshot
                    final List<DocumentSnapshot> documents = snapshot.data.docs;
                    return ListView(
                        children: documents
                            .map((doc) => Card(
                                  child: ListTile(
                                    title: Text(doc['displayName']),
                                    subtitle: Text(doc['plastics'].toString()),
                                  ),
                                ))
                            .toList());
                  } else if (snapshot.hasError) {
                    return Text('Its Error!');
                  }
                });
          }
        });
  }

Is there a specific function needed so that the documents in the Member collection are listed based on the numerical value of the plastics?

Upvotes: 0

Views: 39

Answers (1)

dshukertjr
dshukertjr

Reputation: 18593

You can use orderBy to sort your results.

FirebaseFirestore.instance
                    .collection('Groups')
                    .doc(groupId)
                    .collection('Members')
                    .orderBy('plastics', descending: true)
                    .get()

Upvotes: 1

Related Questions