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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With