Solved: How to do a pass/continue in .map method for Dart?

Question

Asked by darkstar on December 16, 2021 (source).

So basically say I have a class:

class Book {
  late String title;
  late int publishYear;

  Book({required this.title, required this.publishYear});

  factory Book.fromJson(Map<String, dynamic> json) {
    return Book(
      title: json['title'],
      publishYear: json['published'],
    );
  }
}

Now say I want to filter a list of Books by their publish year like so:

void filterByPublishYear() {
  List response = responseData; // API Response

  List<Book> books = response.map((e) {
    Book book = Book.fromJson(e);
    if (book.publishYear > 2000) {
      return book;
    }
  }).toList();
}

The .map() method has an error because it doesn't always return something:

A value of type 'List<Book?>' can't be assigned to a variable of type 'List'. Try changing the type of the variable, or casting the right-hand type to 'List'.

I don't want to set the List to type Book? neither because, well, they're not supposed to be null ever.

How could I make this work? Is there a way to do a continue or a pass for .map() in dart that could make this work?

Thank you!

Answer

Question answered by mmcdon20 (source).

No, there isn't any way to pass or continue from within the callback of a map function. A few alternative ways to approach would be to use a combination of map and where as h8moss points out. Or alternatively you achieve the same result using fold:

List<Book> books = response.fold<List<Book>>([], (prev, element) {
  Book book = Book.fromJson(element);
  if (book.publishYear > 2000) {
    prev.add(book);
  }
  return prev;
});
DART FLUTTER
SHARE: