1

I want a list.forEach and if in forEach and when this if return true I want to break this code like that

  list.forEach((element){
       if(element == "a"){
         break
      }
    })

but it didn't help.

2 Answers2

5

Rewrite your forEach call to a for-each loop:

  for (final element in list) {
    if (element == "a") {
      break;
    }
  }
julemand101
  • 28,470
  • 5
  • 52
  • 48
2

Real answer on a real question about how to break forEach in if.

void main() {
  final seq1 = [0, 1, 2];
  final result = <int>[];
  try {
    seq1.forEach((e) {
      if (e == 2) throw 'Stop this immediately';
      result.add(e);
    });
  } catch (e) {
    // What? Something happened?
  }

  print(result);
}

Result:

[0, 1]

Not the most practical option, but it works.
That is, fully functional, for your case (break forEach).
The answer fully answers your question.
Do you have any other question?

mezoni
  • 10,684
  • 4
  • 32
  • 54