【问题标题】:Dart fold with null safety带零安全的飞镖折叠
【发布时间】:2021-07-11 20:31:02
【问题描述】:

我有以下代码使用列表折叠为同名的人汇总现金。

void main() { 
 List<Map<String,dynamic>> people = [{'name': 'Jim', 'cash':44.86},{'name': 'Jim', 'cash':40.55},{'name': 'Bob', 'cash':10.99},{'name': 'Bob', 'cash':10.99}];
  Map resultAmount = people.fold<Map<String, num>>({}, (totalMap, element) {
    final String key = element['name'];
      if (totalMap[key] == null) totalMap[key] = 0;
      totalMap[key] += element['cash'].toDouble();
      return totalMap;
    });
  print(resultAmount);
}

打印:

{Jim: 85.41, Bob: 21.98}

我怎样才能让它与 null-safety 一起工作?

【问题讨论】:

    标签: flutter dart fold dart-null-safety


    【解决方案1】:

    你可以简化线条

    if (totalMap[key] == null) totalMap[key] = 0;
    

    只需使用 ??= 运算符。

    然后您需要重新设计 totalMap[key] 增量以更好地处理空安全性,因为 Dart 的静态分析并不那么聪明。

    void main() { 
     List<Map<String,dynamic>> people = [{'name': 'Jim', 'cash':44.86},{'name': 'Jim', 'cash':40.55},{'name': 'Bob', 'cash':10.99},{'name': 'Bob', 'cash':10.99}];
      Map<String, num> resultAmount = people.fold<Map<String, num>>({}, (totalMap, element) {
        final String key = element['name'];
        totalMap[key] ??= 0;
        totalMap[key] = element['cash'].toDouble() + totalMap[key];
        return totalMap;
      });
      print(resultAmount);
    }
    

    或者,也许更优雅的解决方案是使用临时变量:

    void main() { 
     List<Map<String,dynamic>> people = [{'name': 'Jim', 'cash':44.86},{'name': 'Jim', 'cash':40.55},{'name': 'Bob', 'cash':10.99},{'name': 'Bob', 'cash':10.99}];
      Map<String, num> resultAmount = people.fold<Map<String, num>>({}, (totalMap, element) {
        final String key = element['name'];
        
        double tmp = totalMap[key]?.toDouble() ?? 0.0;
        tmp += element['cash'].toDouble();
        
        totalMap[key] = tmp;
        return totalMap;
      });
      print(resultAmount);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2013-12-27
      • 2021-06-10
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多