Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Dart's .forEach()?

Tags:

dart

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?

like image 392
Leksat Avatar asked Sep 25 '12 16:09

Leksat


People also ask

How do you stop a forEach flutter?

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.

How do you forEach in darts?

forEach() Function. Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map's entries.

How do you return forEach darts?

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.


1 Answers

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;   } } 
like image 112
John Evans Avatar answered Oct 02 '22 22:10

John Evans