Home > Blockchain >  Why is the BloC model information updated in this case?
Why is the BloC model information updated in this case?

Time:05-23

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.

CodePudding user response:

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(....

CodePudding user response:

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();
}
  • Related