The firstWhere()
method returns the first item in the list that satisfies the condition.
E firstWhere(
bool test(E element),
{E orElse()}
)
This function takes one parameter element
and searches that element in the list.
The method firstWhere()
iterates through the list and returns the first item to satisfy the given condition.
The
orElse()
method is invoked if no element satisfies the condition.
The following code shows how to use the method firstWhere()
in Dart:
void main(){// Creating list languagesList languages = new List();// Adding items to the listlanguages.add('Dart');languages.add('Python');languages.add('Java');languages.add('C#');languages.add('C++');// Print resultprint(languages);// iterate through the list// Returns the first item whose length is greater than 3var val = languages.firstWhere((item) => item.length > 3, orElse: () => null);// if val is null, then the if statement is executedif ( null == val ) {print('Language not found.');}// Display resultprint(val);// Creating another listList<String> fruits = ['Apple', 'Lemon', 'Avocado', 'Orange'];// iterate through the list// Returns the first item that contains PineApple// the orElse() is invoke if not foundvar fav = fruits.firstWhere((item) => item.contains('PineApple'),orElse: () => 'Fruit not available');print(fav);}
null
.PineApple
. orElse()
is invoked if not found.If the
orElse()
method is not specified, aStateError
is thrown by default.