How to stop Dart's .forEach()?

后端 未结 9 1761
星月不相逢
星月不相逢 2020-12-05 09:02
List data = [1, 2, 3];
data.forEach((value) {
  if (value == 2) {
    // how to stop?
  }
  print(value);
});
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 09:38

    Breaking a List

    List example = [ 1, 2, 3 ];
    
    for (int value in example) {
      if (value == 2) {
        break;
      }
    }
    

    Breaking a Map

    If you're dealing with a Map you can't simply get an iterator from the given map, but you can still use a for by applying it to either the values or the keys. Since you sometimes might need the combination of both keys and values, here's an example:

    Map example = { 'A': 1, 'B': 2, 'C': 3 };
    
    for (String key in example.keys) {
      if (example[key] == 2 && key == 'B') {
        break;
      }
    }
    

    Note that a Map doesn't necessarily have they keys as [ 'A', 'B', 'C' ] use a LinkedHashMap if you want that. If you just want the values, just do example.values instead of example.keys.

    Alternatively if you're only searching for an element, you can simplify everything to:

    List example = [ 1, 2, 3 ];
    int matched = example.firstMatching((e) => e == 2, orElse: () => null);
    

提交回复
热议问题