Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter: ListView.builder's trailing IconButton alters items list without being asked to

  • 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)),
                                        );
                                      }),

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading