[dart]Variable values change unintentionally
Situation
There is a class that regulates the operation of the application. The "Change settings" screen takes a copy of the existing instance as an argument and displays the setting values on the screen. Press the "Save" button to replace the copy of this instance with an existing instance. If you return without pressing the "Save" button, the existing instance will be retained.
However, even if you operate it to some extent and return without pressing the "Save" button, the existing instance has been changed.
Cause
When creating the "Change settings" screen, the instance was assigned with =.
In dart (or in most languages like C#), even if you assign a class with =, it will be passed by reference. In other words, the address of the variable is passed, so if you change the value of the assignment destination, the original value will also change.
In the above example, I intend to change the value of the instance copy on the "Change settings" screen, but I have also changed the original instance value, and I do not have to press the "Save" button to replace the instance.
Solution
You need to create a new instance without passing it with =. It seems that there is no method that copies the entire class in dart, so it is convenient to prepare a method that can inherit the original value.
class settingData{
String name;
int id;
//Constructor that copies member variables to create a new instance
settingData.copyFrom(settingData source){
this.name=source.name;
this.id=source.id;
}
}
class SettingPage extends StatefulWidget{
final settingData data;
SettingPage({this.data})
}
//~~~~Some class~~~~~~
Future<void> goToSettingPage(settingData data) async{
await Navigator.of(context).push(new MaterialPageRoute(
builder: (context) =>
// SettingPage(data: data) NG example
SettingPage(data: settingData.copyFrom(data)) //here
));
}
However, this method is not very smart because you have to change the copyFrom() constructor every time you add a new member variable to the settingData class.
Lastly
It's a fairly rudimentary mistake, but I think there are many situations like the one above (using tentative data until the user approves). Be careful when passing variables.
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments