skip to Main Content

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


  1. Call toList when passing the list to navigator

    This will create a new list with the same elements, which means updating the parent list won’t update the newly created one.

    void main() {
      final a = [1,2,3];
      final b = a;
      
      a.add(4);
      print('a: $a');         // a: [1, 2, 3, 4]
      print('b: $b');         // b: [1, 2, 3, 4]
      
      final c = a.toList();
    
      a.add(5);
      print('a: $a');         // a: [1, 2, 3, 4, 5]
      print('c: $c');         // c: [1, 2, 3, 4]
    }
    

    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

    Login or Signup to reply.
  2. If you want to create a new list from reference from previous list,

    List<String> listA = ["apple", "banana", "cat"];
    

    Instead of directly assigning list like:

    List<String> listB = listA;
    

    You can do,

    List<String> listB = List.from(listA);
    

    This will create a completely new list from data of listA and modifying listB will not affect listA.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search