Home > Enterprise >  Multiple lists share same reference
Multiple lists share same reference

Time:06-29

Ive got a function named allAppointmentList to get Appointments from the server using a GET method in AppointmentProvider class. In my MyAppointments class I have initialized 2 lists named as appointment and allAppointments as below,

class _MyAppointmentState extends State<MyAppointment> {
 bool isLoading = true;
 List<Appointment> allAppointments=[];
 List<Appointment> appointments = [];

And in the init state I have assigned the data I get from the allAppointmentList method to the 2 lists mentioned above.

@override
void initState() {
super.initState();
_loadAppointments();
}

_loadAppointments() async {
final AppointmentProvider appointmentProvider =
    Provider.of<AppointmentProvider>(context, listen: false);
await appointmentProvider.getAllAppointments();
setState(() {
  isLoading = false;
  appointments = appointmentProvider.allAppointmentList;
  allAppointments = appointmentProvider.allAppointmentList;
});
}

when I change one list the other changes as well.For example, if I clear the appointments list,allAppoitments list gets cleared as well.If I remove the element in the second index of the appointments list,the element in the second index of the allAppointments list gets removed as well.

How can I make these two list act independently ?

CodePudding user response:

Your problem is probably that you think this creates new lists:

  appointments = appointmentProvider.allAppointmentList;
  allAppointments = appointmentProvider.allAppointmentList;

My guess is that appointmentProvider.allAppointmentList returns the same List instance every time which is a problem here since you are then just assigning the same List object to both appointments and allAppointments.

I am not sure if you also want copies of all the objects inside the lists but if you just want to have independent lists which then contains references to the same objects, the safest would just be to do:

  appointments = appointmentProvider.allAppointmentList.toList();
  allAppointments = appointmentProvider.allAppointmentList.toList();

This will create new lists which then contains the same objects from appointmentProvider.allAppointmentList. But you can then delete/add elements to each of these lists without this change also happening to the other lists.

CodePudding user response:

appointments and allAppointments are currently just references to appointmentProvider.allAppointmentList. You can create new instances as follows:

appointments = [...appointmentProvider.allAppointmentList];
allAppointments = [...appointmentProvider.allAppointmentList];

This uses a list literal [] in combination with the spread operator ... to create a new list with the same elements. Note that the elements themselves are still references to their original instances and are not deep copies.

  • Related