Jonathan
Jonathan

Reputation: 164

How can I sort data by the value of a flutter map?

i'm trying to sort the values i get from my realtime database converted to Map. This is what I get:

    {Table 2:
    {
    order 1:
    {
    WATER: {price: 1.50, quantity: 2},
    date: 2022-12-14 17:34:51.428972}
    },
    
    Table 1:
    {
    order 2:
    {
    date: 2022-12-14 17:35:04.761532,
    COCA COLA: {price: 2, quantity: 1}
    },
    
    order 1:
    {
    DAISY: {price: 7, quantity: 1},
    date: 2022-12-14 17:22:12.678864,
    4 CHEESES: {price: 7, quantity: 1},
    WATER: {price: 1.50, quantity: 2}
    }
    }
    }

What I want is to compare all orders by date so as to get them chronologically, resulting in something like this:

         {Table 1:
         {
         order 1:
         {
         DAISY: {price: 7, quantity: 1},
         dates: 2022-12-14 17:22:12.678864,
         4 CHEESES: {price: 7, quantity: 1},
         WATER: {price: 1.50, quantity: 2}
         },

         Table 2:
         {
         order 1:
         {
         WATER: {price: 1.50, quantity: 2},
         date: 2022-12-14 17:34:51.428972}
         },
        

         Table 1:
         {
         order 2:
         {
         dates: 2022-12-14 17:35:04.761532,
         COCA COLA: {price: 2, quantity: 1}
         },
         },
         }

Upvotes: -1

Views: 436

Answers (1)

Ali Ammar
Ali Ammar

Reputation: 384

you could easily sort any list based on date using this way

newData.sort((a, b) {
    return (a['date'] as DateTime).compareTo(b['date'] as DateTime);
});

but your data is map not list and map does not have a sort or order at all ,

you should change your data structure first into array then sort it somethings like this should work

  final tables = <String, Map<String, Map>>{}; // ...your data here
  final newData = tables.entries
      .map(
        (table) => table.value.entries.map(
          (order) => {"table": table.key, "order": order.key, ...order.value},
        ),
      )
      .expand(
        (element) => element,
      )
      .toList();
  newData.sort((a, b) {
    return (a['date'] as DateTime).compareTo(b['date'] as DateTime);
  });

Upvotes: 1

Related Questions