SOS video
SOS video

Reputation: 476

Sorting data with two orderBy() ​does not work (Flutter)

I am trying to build an flutter applicationwhic should order the data I get from the firestore by the date and by the time values given from the firestore. I tried this code, but now the data doesn't load, but its loading when I comment one of the two orderBy() out. I use the data afterwards in a StreamBuilder.

This is the code:

Firestore.instance
          .collection('customer')
          .document(userUIDglobal)
          .collection('myReservations')
          .orderBy('date')
          .orderBy('time')
          .snapshots(),

After getting the data, I display it in a StreamBuilder with this code:

return ListView.builder(
          itemCount: snapshot.data.documents.length,
          itemBuilder: (context, index) {
            DocumentSnapshot reservation = snapshot.data.documents[index];
            return ListTile(
              title: Text(reservation['date'].toString()),
              subtitle: Text(reservation['time'].toString()),
            );
          },
        );

Here is the code for formatting the date:

String formatedDatee = new DateFormat('yyyy-MM-dd').format(pickedDate);

Here is the code for formatting the time:

data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),

On the screenshot you can see my firestore:

enter image description here

Here is a screenshot where you can see how the screen lokks when I try runnung the code:

enter image description here

And this is a screenshot when I comment one of the two .orderBy() out:

enter image description here

Does anyone know how to solve this problem?

Upvotes: 1

Views: 358

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599926

Your date and time fields are stored as string values, in a format that is not useful for sorting. In string sorting, 07.11.2020 is after 06.10.2020. While you and I may see that these are dates: the database has no idea.

The best solution is usually to store the date/time as a DateTime field. Alternatively, you can keep your current fields, but store the values in a format that does allow sorting them usefully, e.g. 2020-11-07 and 18:58. If you sort dates and time strings in these formats, their values are also chronological.

Upvotes: 1

Related Questions