0

Creating a page to edit a user's profile I initialize a variable with the user's information stored in a model and create a user with that information to edit it:

late UserModel user;
late UserModel userUpdate;

@override
void initState() {
   user = BlocProvider.of<UserBloc>(context).user;
   UserModel userUpdate = new UserModel(
      id: user.id,
      phones: user.phones
   );

   super.initState();
}

I display the phones in a list next to a button that deletes the phone of my choice. The onpressed button does exactly this:

onPressed: () {
   setState(() {
      userUpdate.phones.remove(userUpdate.phones[index]);
   });
},

In the appBar there are 2 options, return without saving and save. If I choose the option without saving, I simply do a Navigator.pop(context);

Here is my problem, when deleting a phone from the list, I expect it to be removed from the userUpdate object and when returning without saving nothing happens. However, if I go back to the edit user profile page, that phone has been removed from the main model, the one I initialize in the user variable. Why does this happen?

Summary: I edit an object '2' created from object '1', update a value of object '2' and object '1' is updated.

ivangl
  • 35
  • 4
  • The code you show would not show this behaviour, it would throw an exception. Please post a [mcve], either we are missing an important piece of your code, or you did not post the latest version. – nvoigt May 23 '22 at 06:08

2 Answers2

0

Taking in count the code you've shared, this variable late UserModel userUpdate; is never assigned, because is being shadowed in the intState by this other assignment UserModel userUpdate = new UserModel(....

I think it should be this.userUpdate = new UserModel(....

Gauris Javier
  • 387
  • 4
  • 11
0

userUpdate you created inside initState() cannot call outside this,

create other user variable if you want use

late UserModel user;
late UserModel userUpdate;
UserModel defaultUser = UserModel(
      id: user.id,
      phones: user.phones
   );

@override
void initState() {
   user = BlocProvider.of<UserBloc>(context).user;
   super.initState();
}
Xuuan Thuc
  • 2,340
  • 1
  • 5
  • 22