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!
CodePudding user response:
Sounds to me like what you want is a where
method:
List<Book> books = [
Book(title: "Harry Potter", publishYear: 1997),
Book(title: "Diary of a Wimpy Kid", publishYear: 2007),
];
books = books.where((e) => e.publishYear > 2000).toList()
The where method takes a function like map
, but it returns a bool, if the bool is true, it keeps the item, if it's false, it drops it from the list.
CodePudding user response:
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;
});