Home > Back-end >  How to sort a list with Firestore Flutter?
How to sort a list with Firestore Flutter?

Time:03-12

When creating notes, they are displayed in a different order for me. Notes taken from Firestore. Can I sort the list and display data by creation date, from oldest to newest? I am getting data from firestore

list_note_page.dart

Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: snapshot.data?.docs.length,
        itemBuilder: (context, index) {
          QueryDocumentSnapshot<Object?> documentSnapshot =
              snapshot.data!.docs[index];
          return Dismissible(
              key: Key(documentSnapshot.id),
              direction: DismissDirection.endToStart,
              onDismissed: (direction) {
                Database().deleteNote(documentSnapshot.id);
              },
              background: Container(
                padding: const EdgeInsets.only(right: 20),
                alignment: Alignment.centerRight,
                color: Colors.red,
                child: const Text(
                  'Delete',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ),
              child: ListTile(
                onTap: () => Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: ((context) => AddAndEditNotePage(
                              header: documentSnapshot['name'],
                              title: documentSnapshot['title'],
                              date: documentSnapshot['date'],
                              id: documentSnapshot.id,
                            )))),
                title: Text(documentSnapshot['name']),
                subtitle: Text(documentSnapshot['title']),
                trailing: Text(documentSnapshot['date'] ?? ''),
              ));
        });
  }

CodePudding user response:

I recommend to add an additional field to your documents, perhaps called created_date that will take a timestamp of the time when you push it to Firebase, (unless that date field you have there is the creation date of that document) then you can do:

Firestore.instance
          .collection('YOUR_COLLECTION')
          .orderBy('created_date').get()

By default, the descending order is false (oldest to newest).

Check this link or this for further reference.

  • Related