How to stop Dart's .forEach()?

后端 未结 9 1768
星月不相逢
星月不相逢 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: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;
        }
      }
    }
    

提交回复
热议问题