How to find an element in a dart list

Use firstWhere method: https://api.flutter.dev/flutter/dart-core/Iterable/firstWhere.html

void main() {
  final list = List<Book>.generate(10, (id) => Book(id));

  Book findBook(int id) => list.firstWhere((book) => book.id == id);

  print(findBook(2).name);  
  print(findBook(4).name);
  print(findBook(6).name);  
}

class Book{
  final int id;

  String get name => "Book$id";

  Book(this.id);
}

/*
Output:
Book2
Book4
Book6
*/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)