I have a list on Screen A
I Navigate to Screen B passing list on Screen A and modify few fields in the list in Screen B
And I press back.
Then the Screen A list is also getting updated.
I need to prevent updating Screen A list unless I manually update the list in Screen A
I am using Navigator to navigate to Scree A
Navigator.push used to pass the Screen A list to Screen B
I modify Screen B list and click on back
Screen A list should not update.
class PayeeList {
List<PayeeData>? data;
}
class PayeeData {
int? id;
PayeeAttributes? attributes;
}
class PayeeAttributes {
num? amount;
String? createdAt;
String? updatedAt;
User? user;
}
Initial list as follow with some data
List<PayeeData>? data = [];
List<PayeeData> payees= data.toList();
var result = await Navigator.push(context,
MaterialPageRoute(builder: (context) => MultiBlocProvider(
providers: [
//REMOVED for sharing in stack overflow
],
child: ExpensePayeesScreen(
title: "Payees",
isEdit: false,
paidAmounts:payees,
totalAmount: 100))),
);
When I return from screen B the data list getting updated
———–SOLVED———–
I solved issue by creating the passing temp array as below
List<PayeeData> temp = [];
expenseData.attributes?.payees?.data?.forEach((element) {
PayeeAttributes payeeAttributes = PayeeAttributes(amount: element.attributes?.amount ?? 0, user: element.attributes?.user ?? User());
temp.add(PayeeData(id: element.id, attributes: payeeAttributes));
});
2
Answers
Call
toList
when passing the list to navigatorThis will create a new list with the same elements, which means updating the parent list won’t update the newly created one.
You can also see other methods to create a new list in that manner here: How to copy list values to another list in flutter
There’s also an explanation of why that happens in an answer in that question: https://stackoverflow.com/a/58389737/10210069
If you want to create a new list from reference from previous list,
Instead of directly assigning list like:
You can do,
This will create a completely new list from data of listA and modifying listB will not affect listA.