dart 如何按Flutter图的值对数据进行排序?

pprl5pva  于 2022-12-15  发布在  Flutter
关注(0)|答案(1)|浏览(176)

我试图排序的值我从我的实时数据库转换成Map。这是我得到的:

{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}
    }
    }
    }

我想要的是按日期比较所有订单,以便按时间顺序得到它们,结果如下:

{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}
         },
         },
         }
watbbzwu

watbbzwu1#

你可以很容易地排序任何列表基于日期使用这种方式

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

但是你的数据是Map而不是列表,并且Map根本没有排序或顺序,
你应该先把你的数据结构改成数组,然后排序,这样就行了

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);
  });

相关问题