Luis Cardoza Bird
Luis Cardoza Bird

Reputation: 1472

Flutter: Break forEach with switch and recursive call

I know that this question was already asked: breaking out of a switch within a foreach loop closure

however for some reason the suggested answer won't solve the issue, and the other difference is that im referencing the same function recursively.

Future<bool> checkSignatures(List<Widget> widgets) async {
  dynamic converted;
  bool _result = false;
  loop:
  for (var value in widgets) {
    switch (value.runtimeType) {
      case SignatureCreator:
        converted = value as SignatureCreator;
        if (await converted.data == null || await converted.data == "") {
          _result = true;
          break loop;
          break;
        }
        break;
      case PagerParserWidget:
        converted = value as PagerParserWidget;
        checkSignatures(converted.widgets);
        break;
      case ColumnParserWidget:
        converted = value as ColumnParserWidget;
        checkSignatures(converted.widgets);
        break;
    }
  }
  return _result;
}

i apply the suggestion of added a label to the loop and then break it, it display the result true but only at the end and is replaced by the others values inside the recursive call.

I/flutter ( 5464): S: false

I/flutter ( 5464): S: false

I/flutter ( 5464): S: true

when only it should display true once, due to an empty/null value.

Upvotes: 0

Views: 661

Answers (1)

Pieter van Loon
Pieter van Loon

Reputation: 5648

Instead of setting the result variable you can return true. And then also make sure that you use the returned value when calling the method recursively. So you get: if (await checkSignatures(...)) return true;

Upvotes: 1

Related Questions