What is the List firstWhere() method in Dart?

The firstWhere() method returns the first item in the list that satisfies the condition.

Syntax

E firstWhere(
bool test(E element),
{E orElse()}
)

Parameter

This function takes one parameter element and searches that element in the list.

Return value

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.

Code

The following code shows how to use the method firstWhere() in Dart:

void main(){
// Creating list languages
List languages = new List();
// Adding items to the list
languages.add('Dart');
languages.add('Python');
languages.add('Java');
languages.add('C#');
languages.add('C++');
// Print result
print(languages);
// iterate through the list
// Returns the first item whose length is greater than 3
var val = languages.firstWhere((item) => item.length > 3, orElse: () => null);
// if val is null, then the if statement is executed
if ( null == val ) {
print('Language not found.');
}
// Display result
print(val);
// Creating another list
List<String> fruits = ['Apple', 'Lemon', 'Avocado', 'Orange'];
// iterate through the list
// Returns the first item that contains PineApple
// the orElse() is invoke if not found
var fav = fruits.firstWhere((item) => item.contains('PineApple'),
orElse: () => 'Fruit not available');
print(fav);
}

Explanation

  • Line 2: We create the list.
  • Line 4 to 10: We add elements to the list.
  • Line 11: We print the element of the list.
  • Line 14: We iterate through the list and return the first item whose length is greater than 3.
  • Line 15: We print the message “Language not found” if the value is null.
  • Line 23: We create the list of fruits.
  • Line 27: We iterate through the list and return the first item that contains PineApple. orElse() is invoked if not found.

If the orElse() method is not specified, a StateError is thrown by default.

Free Resources