Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dictionary 减少/过滤Dart中地图的首选方法?_Dictionary_Dart - Fatal编程技术网

Dictionary 减少/过滤Dart中地图的首选方法?

Dictionary 减少/过滤Dart中地图的首选方法?,dictionary,dart,Dictionary,Dart,试图找到在Dart中缩小地图的最干净的方法。寻找类似JavaScript的东西 有什么建议吗?以下方法还有很多需要改进的地方: Map ingredients = { 'flour': '250g', 'butter': '50g', 'egg': 1, 'water': '0.2l' }; final flour = new Map.fromIterable( ingredients.keys.where((k) => ingredients[k] == '250g

试图找到在Dart中缩小地图的最干净的方法。寻找类似JavaScript的东西

有什么建议吗?以下方法还有很多需要改进的地方:

Map ingredients = {
  'flour': '250g',
  'butter': '50g',
  'egg': 1,
  'water': '0.2l'
};

final flour = new Map.fromIterable(
  ingredients.keys.where((k) => ingredients[k] == '250g'),
  value: (k) => ingredients[k]
);

print(flour); // {flour: 250g}

核心库中没有对成对的内置支持。然而,如果您发现自己经常做这类事情,您可以编写一个实用程序库。例如:

library pairs;

class Pair<K,V> {
  Pair(this.k, this.v)
    final K k;
    final V v;
    String toString() => '($k, $v)';
}

Iterable<Pair> asPairs(Map map) => map.keys.map((k) => new Pair(k, map[k]));

Map fromPairs(Iterable<Pair> pairs) => new Map.fromIterables(
    pairs.map((p) => p.k),
    pairs.map((p) => p.v));
也许这是一些可以贡献给一组非核心实用程序的东西

import 'src/pairs.dart';

Map flour = fromPairs(asPairs(ingredients).where((p) => p.v == '250g'));

print(flour); // {flour: 250g}