How to sort datas from firestore to a map by date in flutter

Viewed 6676

I am trying to sort a list of events in my firestore into a map. like this

Map<DateTime, List> _events;
_events = {
DateTime.parse('2019-06-30'): ['Event 1', 'Event 2'],
DateTime.parse('2019-06-20'): ['Event 3', 'Event 4'],
}

i have firestore data documents as events which have fiels

name: 'Event 1'
date: '2019-06-20'

name: 'Event 2'
date: '2019-06-30'

name: 'Event 3'
date: '2019-06-20'

name: 'Event 4'
date: '2019-06-20'

each in different documents

How can i make these happen using firebase

    QuerySnapshot querySnapshot = await Firestore.instance
        .collection('${_username.toLowerCase()}-orders')
        .orderBy('date', descending: true)
        .getDocuments();
    var damap = querySnapshot.documents;
    print('damap $damap');

i want to make this damap variable data to _events as above format how can i do that

1 Answers

Since you store your dates with the YYYY-MM-DD format, you can sort these strings lexicographically descending or ascending and then you can use the orderBy method, as follows:

Firestore.instance
          .collection('${_username.toLowerCase()}-orders')
          .orderBy('date', descending: true)
          .snapshots()
          .listen((data) {...})
Related