带空安全的飞镖折叠

Dart fold with null safety

我有以下代码,使用 list fold 为同名的人汇总现金。

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}

我怎样才能让它与空安全一起工作?

你可以简化行

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