I’m working on a Flutter project in which the architecture forces me to use an instance of a class, say UserModel
, as a value attached to the BuildContext
. In this way, I can access that class in every part of the app.
Anyway, there are moments in which I want to update the UserModel
, and not only by changing the value of some of the fields, but updating all of them. At this moment, I am using an horrible function, let’s call that updateUser(final UserModel newInstance)
. It follows an example.
class UserModel {
String name, surname;
UserModel({required this.name, required this.surname});
void updateUser(final UserModel newInstance) {
name = newInstance.name;
surname = newInstance.surname;
}
}
The main problem with this solution is that it often happens that I add some fields to the UserModel
class, but I forgot to add them to updateUser
. Also, the solution I am using looks horrible.
I know that many of you could say that I should enclose the instance of UserModel
in a UserModelProvider
class and just replace the value of the userModel
field. This would not be compatible with the architecture of the software I am developing, so please don’t suggest me that.
2
Answers
I got it sorted out. The main point to understand is to use reflection, the ability of a program to examine and modify its own structure, behavior, and metadata at runtime.
To do so, I edit my
updateUser
function to be able to loop through the class variables and set them in the new instance. Here is the result.So now I can use an instance of the class to update itself, for instance by fetching new values from Firestore. It follows an example of the functioning.
And this is crucial if my
UserModel
is being served byProvider
, and therefore attached to theBuildContext
.To be honest, it’s hard to understand your issue.
If I’m not wrong, you are looking for
copyWith
method.With this method, you will be able to update one or both variable.
Updated
I don’t know why you force to update it, the concept is the same.
As I said in the comments, you update the instance, not the object model.
foo
is an instance ofUserModel