What is the List firstWhere() method in Dart?

Posted by

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);
 }

Output

 [Dart, Python, Java, C#, C++]
 Dart
 Fruit not available
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x