Adding the orElse function to the firstWhere method

I am trying to add the onElse function to the itterator.firstWhere method, but I cannot get the syntax correctly.

I tried something like

List<String> myList = 

String result = myList.firstWhere((o) => o.startsWith('foo'), (o) => null);

But the compiler has an error

Expected 1 positional arguments, but 2 found

I'm sure this is a simple syntax problem, but it puzzled me

+4
source share
1 answer

'orElse' is a named optional argument.

void main() {
  checkOrElse(['bar', 'bla']);
  checkOrElse(['bar', 'bla', 'foo']);
}

void checkOrElse(List<String> values) {
  String result = values.firstWhere((o) => o.startsWith('foo'), orElse: () => '');

  if (result != '') {
    print('found: $result');
  } else {
    print('nothing found');
  }
}
+8
source

All Articles