skip to Main Content

I am building a list of data of type List<Map<String, dynamic>> (which I am getting from firebase documents all of which have the following data: document fields). Once I get all the data I would like to sort the list by the createdOn field (which is a timestamp) but I’m unsure as to how to sort it. Here’s a snippet of code showing how I build the list:

Future<List<Map<String, dynamic>>>? getData(List<String> subcategory) async {
    List<Map<String, dynamic>> allData = [];
    try {
      String? email = FirebaseAuth.instance.currentUser!.email;
      var categories = Utils.categoriesDropdownItems;
      for (var i = 0; i < subcategory.length; ++i) {
        var doc = await FirebaseFirestore.instance
            .collection(email!)
            .doc(categories[0])
            .collection(subcategory[i])
            .get();
        allData.addAll(doc.docs.map((doc) => doc.data()).toList());
      }
      allData.sort(); //Unsure how to approach sorting by timestamp??
      

I’m unsure how to extract the created on field to be able to sort it. I tried doing something like:

allData.sort((a, b) => a["cretedOn"].compareTo(b["createdOn"]));

but it seems like compareTo does not exist for a["createdOn"]?

2

Answers


  1. Chosen as BEST ANSWER

    Solved. I just had to make sure the timestamps were defined as follows:

    allData.sort(((a, b) {
        Timestamp one = a["createdOn"];
        Timestamp two = b["createdOn"];
        return two.compareTo(one);
      }));
    

  2. You can order them directly in your firestore query using orderBy like this

    .collection(subcategory[i]).orderBy('createdOn', descending: true);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search