Home > Back-end >  Flutter: ListView.builder's trailing IconButton alters items list without being asked to
Flutter: ListView.builder's trailing IconButton alters items list without being asked to

Time:07-15

  • I have two identical lists initiated with the same data: freeBooks and updatedFreeBooks.
  • I am trying to return a ListView.Builder made of elements from the freeBooks List.
  • Each ListTile has a trailing IconButton which removes the item from the updatedFreeBooks List, but NOT from the freeBooks List.
  • YET for some reason pressing the trailing IconButton is also removing the element from the freeBooks list and updating the ListView WITHOUT BEING ASKED TO. WHY???

How can I ensure that the code doesn't alter the original freeBooks List? Here's the code sample:

                                  child: ListView.builder(
                                      itemCount: freeBooks.length,
                                      itemBuilder: (context, index) {
                                        String novelTitle = novel.title;
                                        return ListTile(
                                          title:
                                              Text('$novelTitle'),
                                          trailing: IconButton(
                                              onPressed: () {
                                                setState(() {
                                                  updatedFreeBooks
                                                      .removeAt(index);
                                                });
                                              },
                                              icon: Icon(Icons.cancel)),
                                        );
                                      }),

CodePudding user response:

Use updatedFreeBooks=List.of(user.fbooks)

Objects are passed by reference. When you do list1 = list; and list2 = list;, you're assigning the reference of list to both list1 and list2. So changing the object at that reference will change the data you see at all of these different variables.

  • Related