2

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.

1
  • any update for this? Commented Mar 7, 2021 at 6:20

3 Answers 3

2

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

if (bookList is List<Book>) { 
    print("Yes");
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.