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.
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
*/
If the searched item might or might not be in the array, with null safety I personally prefer to use .where
on lists - it filters through the array and returns a list.
var myListFiltered = myList.where((e) => e.id == id);
if (myListFiltered.length > 0) {
// Do stuff with myListFiltered.first
} else {
// Element is not found
}
The benefit of this approach is that you'll always get an array and there won't be an issue with element not being found or trying to return null
through orElse
callback:
The return type 'Null' isn't a 'FooBar', as required by the closure's context.
Since the task of finding an element by id in a list of objects is quite a common one, I like to extract that logic into helpers file, for example:
class Helpers {
static findById(list, String id) {
var findById = (obj) => obj.id == id;
var result = list.where(findById);
return result.length > 0 ? result.first : null;
}
}
And use it like this:
var obj = Helpers.findById(myList, id);
if (obj == null) return; //? Exn: element is not found
A lot has been said already, but I want to add my best way to do this. if it's possible that the item doesn't exist in the list, import the iterable extension and use firstWhereOrNull1
on the list.
import 'package:collection/src/iterable_extensions.dart';
myList.firstWhereOrNull((item) => item.id == id))
You should add orElse to avoid exeption:
list.firstWhere(
(book) => book.id == id,
orElse: () => null,
});
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