Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

How to properly generate a list from other two lists according to a condition in Flutter

I am trying to generate a list called selectedBooks based on other two lists:

This is the first list:

    List<Book> availableBooks = [
       Book(
        id: 1,
        isActive: false,
        name: "Tipo 1"
       ),
       Book(
        id: 2,
        isActive: false,
        name: "Tipo 2"
       ),
       Book(
        id: 3,
        isActive: false,
        name: "Tipo 3"
       ),
       Book(
        id: 4,
        isActive: false,
        name: "Tipo 4"
       ),
    ]

This is the second list:

    List<Book> allowedBooks = [
       Book(
        id: 1,
        isActive: true,
        name: "Tipo 1"
       ),
       Book(
        id: 3,
        isActive: true,
        name: "Tipo 3"
       ),
    ]

And this is the list I'm trying to generate:

       selectedBooks = availableBooks
          .map((book) =>
              allowedBooks.contains(book.id)
                  ? Book(
                      id: book.id,
                      isActive: true,
                      name: book.name)
                  : Book(
                      id: book.id,
                      isActive: false,
                      name: book.name))
          .toList();

Since allowedBooks does contain id 1 and 3, I am expecting selectedBooks to be:

    List<Book> selectedBooks = [
       Book(
        id: 1,
        isActive: true,
        name: "Tipo 1"
       ),
       Book(
        id: 2,
        isActive: false,
        name: "Tipo 2"
       ),
       Book(
        id: 3,
        isActive: true,
        name: "Tipo 3"
       ),
       Book(
        id: 4,
        isActive: false,
        name: "Tipo 4"
       ),
    ]

However, this doesn't work because selectedBooks ends up having all book.isActive set to false.

I assume something is not working as expected in the condition here included:

selectedBooks = availableBooks
          .map((book) =>
              allowedBooks.contains(book.id) ? ...

Any clue? Thanks a lot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of allowedBooks.contains(book.id) you should use allowedBooks.any((allowedBook) => allowedBook.id == book.id)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...