Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding orElse function to firstWhere method

Tags:

dart

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

I have tried something like

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

But the compiler has an error of

1 positional arguments expected, but 2 found

I am sure it is a simple syntax problem, but it has me stumped

like image 310
richard Avatar asked Oct 22 '14 09:10

richard


People also ask

How do you use firstWhere in flutter?

firstWhere method Null safetyReturns the first element that satisfies the given predicate test . Iterates through elements and returns the first to satisfy test . If no element satisfies test , the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.

What is firstWhere?

The firstWhere method will loop through all the elements of the queue in the iteration order and check each element against the test condition. It will return the first element that satisfies the provided predicate function.


2 Answers

In case someone came here thanks to google, searching about how to return null if firstWhere found nothing, when your app is Null Safe, use the new method of package:collection called firstWhereOrNull.

import 'package:collection/collection.dart'; // You have to add this manually, for some reason it cannot be added automatically  // somewhere... MyStuff? stuff = someStuffs.firstWhereOrNull((element) => element.id == 'Cat'); 

About the method: https://pub.dev/documentation/collection/latest/collection/IterableExtension/firstWhereOrNull.html

like image 102
Wahyu Avatar answered Sep 19 '22 09:09

Wahyu


'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');   } } 
like image 36
Günter Zöchbauer Avatar answered Sep 21 '22 09:09

Günter Zöchbauer