Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element in dart list

Tags:

dart

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.

like image 763

4 Answers

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
*/
like image 121
Kahou Avatar answered Oct 01 '22 04:10

Kahou


Null-Safe approach (handling no-element error)

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.

Refactoring the finder logic into a helper method

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
like image 23
ego Avatar answered Oct 01 '22 05:10

ego


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))
like image 20
Alex Shnyrov Avatar answered Oct 01 '22 04:10

Alex Shnyrov


You should add orElse to avoid exeption:

list.firstWhere(
 (book) => book.id == id,
 orElse: () => null,
});
like image 35
Vladyslav Ulianytskyi Avatar answered Oct 01 '22 05:10

Vladyslav Ulianytskyi