dart

How to find an element in a dart list


I have a dart list of objects, every of which contains book_id property, and I want to find an element of that list by the book_id field.


Solution

  • 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
    */