List data = [1, 2, 3]; data.forEach((value) { if (value == 2) { // how to stop? } print(value); });
I tried return false;
which works in jQuery, but it does not work in Dart. Is there a way to do it?
To break the forEach loop in dart we use the try-catch clause. Here are the steps to achieve this. Wrap the whole forEach loop inside a try block. On the step, you want to break, throw an exception.
forEach() Function. Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map's entries.
There is no way to return a value from forEach . Just use a for loop instead. On top of that, the Dart style guide specifically recommends using a for loop over a forEach unless you can reuse an existing function.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With