如何对从Dart / Flutter中的List.generate方法获得的列表进行排序?

I'm new to dart/flutter. There is a list generated using List.generate method which returns a dictionary. Now, I want to sort the list by 'day' key values as 'Sun, Mon, ...., Sat' as shown in the following piece of code.

final filteredTransactions = List.generate(7, (index) {
      final weekDay = DateTime.now().subtract(Duration(days: index));
      var totalSum = 0.0;
      for (var i = 0; i < recentTransactions.length; i++) {
        if (recentTransactions[i].date.day == weekDay.day &&
            recentTransactions[i].date.month == weekDay.month &&
            recentTransactions[i].date.year == weekDay.year) {
          totalSum += recentTransactions[i].amount;
        }
      }
      return {'day': DateFormat.E().format(weekDay), 'amount': totalSum};
    })

最近交易是一个包含对象日期和金额数据的列表。如何按“天”对filteredTransactions进行排序?谢谢。

评论
  • 小鸡鸡
    小鸡鸡 回复

    You can give List.sort() a custom sort method like this:

    void main() {
      final list = [
        {'day': DateTime(2020, DateTime.april, 04), 'amount': 3},
        {'day': DateTime(2020, DateTime.april, 02), 'amount': 5},
        {'day': DateTime(2020, DateTime.april, 05), 'amount': 2},
        {'day': DateTime(2020, DateTime.april, 03), 'amount': 4}
      ];
    
      list.sort(
          (m1, m2) => (m1['day'] as DateTime).compareTo(m2['day'] as DateTime));
    
      list.forEach(print);
      // {day: 2020-04-02 00:00:00.000, amount: 5}
      // {day: 2020-04-03 00:00:00.000, amount: 4}
      // {day: 2020-04-04 00:00:00.000, amount: 3}
      // {day: 2020-04-05 00:00:00.000, amount: 2}
    }