Heero Yuy
Heero Yuy

Reputation: 614

How to check if Dart List contains certain object instance?

I have a Dart List<Book> bookList; Somewhere in the code it has been filled with books.

How can I check if the bookList contains an instance of a Book? I tried this

if(bookList.contains(Book))

But it didn't work.

Upvotes: 2

Views: 1906

Answers (3)

tafaust
tafaust

Reputation: 1518

First of, you annotated the type of your bookList with List<Book> meaning that any instance should be a Book or null when the list is not empy.

As many others pointed out already, the is is used to test if an object has a specified type. In your case that does not fully solve your problem. If your list contains null, the code

if (bookList is List<Book>) { 
    print("Yes");
}

will produce Yes. You have to check it like so:

class Book {
  String title;
  Book(this.title);
}

void main() {
  List<Book> bookList = [
    Book('foo'),
    null,
  ];

  if ((bookList?.length != 0 ?? false) && (!bookList?.contains(null) ?? false) && bookList is List<Book>) { 
    print("Yes");
  } else {
    print("No");
  }
}

to provide null-safety.

EDIT Updated my answer to be null safe towards bookList being null.

Check the docs:

Upvotes: 0

Thierry
Thierry

Reputation: 8393

You could test the following:

if (bookList.every((item) => item != null && item is Book)) {
   ...
}

If your bookList is by design a List, testing for nullity is enough:

if (bookList.every((item) => item != null)) {
  ...
}

If you want to prevent null elements inside the list, you should enforce it also when you add/update element to your list.

Upvotes: 0

John Joe
John Joe

Reputation: 12803

You can use is to check the type of the List.

if (bookList is List<Book>) { 
    print("Yes");
}

Upvotes: 2

Related Questions