How to stop Dart's .forEach()?

后端 未结 9 1717
星月不相逢
星月不相逢 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:32

    You can also use a for/in, which implicitly uses the iterator aptly demonstrated in the other answer:

    List data = [1,2,3];
    
    for(final i in data){
      print('$i');
      if (i == 2){
        break;
      }
    }
    
    0 讨论(0)
  • 2020-12-05 09:38

    Breaking a List

    List<int> 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<String, int> 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<int> example = [ 1, 2, 3 ];
    int matched = example.firstMatching((e) => e == 2, orElse: () => null);
    
    0 讨论(0)
  • 2020-12-05 09:39

    It is also possible to implement your example using forEach() and takeWhile().

    var data = [1, 2, 3];
    data.takeWhile((val) => val != 2).forEach(print);
    
    0 讨论(0)
  • 2020-12-05 09:39

    The callback that forEach takes returns void so there is no mechanism to stop iteration.

    In this case you should be using iterators:

    void listIteration() {
      List data = [1,2,3];
    
      Iterator i = data.iterator;
    
      while (i.moveNext()) {
        var e = i.current;
        print('$e');
        if (e == 2) {
          break;
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-05 09:41

    You can use for and indexOf

     for (var number in id) {
        var index = id.indexOf(number);
    
        print('Origin forEach loop');
    
        for (int i = 0; i < 1; i++) {
          print("for loop");
        }
    
        break;
      }
    
    0 讨论(0)
  • 2020-12-05 09:46

    Here is a full sample by for-in loop, that close to forEach style.

    void main(){
      var myList = [12, 18, 24, 63, 84,99];
    
      myList.forEach((element) {
       print(element);
       if (element ==24); //break; // does not work
      });
    
     for(var element in myList) {
        print(element);
        if (element==24) break;
       } 
    } 
    
    0 讨论(0)
提交回复
热议问题