Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve an element of a list that satisfy a condition

Tags:

dart

This is my model class:

class Contact {
  String name;
  String email;
  int phoneNo;

  Contact(this.name, this.email, this.phoneNo);
}

Suppose I have a list of contacts like below:

List<Contact> contacts = [
  new Contact('John', '[email protected]', 002100),
  new Contact('Lily', '[email protected]', 083924),
  new Contact('Abby', '[email protected]', 103385),
];

I want to get John's phone number from contacts List, how can I do that?

like image 782
Blasanka Avatar asked Dec 01 '22 14:12

Blasanka


1 Answers

singleWhere throws if there are duplicates or no element that matches.

An alternative is firstWhere with orElse https://api.dartlang.org/stable/1.24.3/dart-core/Iterable/firstWhere.html

var urgentCont = contacts.firstWhere((e) => e.name == 'John', orElse: () => null);
print(urgentCont?.phoneNo?.toString()?.padLeft(6, '0') ?? '(not found)');//Output: 002100
like image 170
Günter Zöchbauer Avatar answered Dec 05 '22 02:12

Günter Zöchbauer