1

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"]?

3 Answers 3

3

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);
  }));
Sign up to request clarification or add additional context in comments.

Comments

0

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

.collection(subcategory[i]).orderBy('createdOn', descending: true);

Comments

0

You can use the sort method with a custom comparison function.

 void main() {
  List<Map<String, dynamic>> data = [
    {'timestamp': 1639791020, 'value': 'Item 1'},
    {'timestamp': 1639794320, 'value': 'Item 2'},
    {'timestamp': 1639792120, 'value': 'Item 3'},
    // Add more items as needed
  ];

  // Sorting the list based on the 'timestamp' field in descending order
  data.sort((a, b) => b['timestamp'].compareTo(a['timestamp']));

  // Printing the sorted list
  print(data);
}

I hope this will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.