How to stop Dart's .forEach()?

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

    Dart does not support non-local returns, so returning from a callback won't break the loop. The reason it works in jQuery is that each() checks the value returned by the callback. Dart forEach callback returns void.

    http://docs.jquery.com/Core/each

    0 讨论(0)
  • 2020-12-05 09:50

    Using Multiple Loop

    Break Outer Loop

    OUTER: for (var i = 0; i < m.length; i++) {
      for (var j = 0; j < m[i].length; j++) {
        if (m[i][j] < 0) {
          print("Negative value found at $i,$j: ${m[i][j]}");
          break OUTER;
        }
      }
    }
    

    Continue Outer Loop

      outer: for (var v in a) {
        for (var w in b) {
          if (w == v) continue outer;
        }
        print(v);
      }
    
    0 讨论(0)
  • 2020-12-05 09:58

    based on Greg Lowe post, I used where for my project and also it works.

    var data = [1, 2, 3];
    data.where((val) => val != 2).forEach(print);
    
    0 讨论(0)
提交回复
热议问题