Home > Net >  remove() from list impact the list got it by provider! [flutter]
remove() from list impact the list got it by provider! [flutter]

Time:02-27

I created a local variable list in a function like this :

 List<FirestoreUser> _members = [];
     _members = Provider.of<GroupsData>(context, listen: false)
              .members(widget.groupID!);

then I created a listview to display the list :

ListView.builder(
                            shrinkWrap: true, 
                            primary: false, 
                            itemCount: _members.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(_members[index].name),
                                trailing: IconButton(
                                    onPressed: () {
                                      setState(() {                                            
                                        print("before remove :"  
                                            Provider.of<GroupsData>(context,
                                                    listen: false)
                                                .members(widget.groupID!)
                                                .toString());
                                        _members.removeAt(index);
                                        print("After remove :"  
                                            Provider.of<GroupsData>(context,
                                                    listen: false)
                                                .members(widget.groupID!)
                                                .toString());
                                      });
                                    },
                                    icon: Icon(Icons.delete)),
                              );
                            },
                          ),

but when I tried to remove an item from the variable list "_members" the item get deleted also from the list in groupData from the provider

Screenshot from the Debug console

Thanks for helping!

CodePudding user response:

This is how lists work in dart. Accessing a list list1 = list2 provides a reference to list2, not a copy.

You can use the .toList() method to create a copy of the list so that the original list is not updated when you make changes to the new list.

See this example:

void main() {
  
  final List<int> list1 = [1,2,3];
  print('list1: $list1'); // prints list1: [1, 2, 3]
  
  // Provides a reference to list1
  final list2 = list1;
  print('list2: $list2'); // prints list2: [1, 2, 3]
  
  list2.remove(2);
  print('list1: $list1'); // prints list1: [1, 3]
  print('list2: $list2'); // prints list2: [1, 3]
  
  // Create a copy of list 1
  final list3 = list1.toList();
  list3.add(4);
  print('list3: $list3'); // prints list3: [1, 3, 4]
  print('list1: $list1'); // prints list1: [1, 3]

}
  • Related