Which is the better way to manipulate form data ? With immutability (with finak keyword on property models) or not ?
Model class immutable:
class Contact {
final String id;
final String name;
// many fields
Contact({this.id, this.name});
}
OR Model class without final keyword :
class Contact {
String id;
String name;
// many fields
Contact({this.id, this.name});
}
The model class Contact is loaded from database in this dummy example;
Here I use Contact model with immutability (with final keyword), and make a copy of the Contact, for every attribute change state:
...
Contact contact;
@override
void initState() {
// load from database
contact = Provider.of<ContactProvider>(context, listen: false).findContactExample();
super.initState();
}
...
Form(
key: _form,
child: ListView(
children: <Widget>[
....
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
initialValue: contact.name,
onSaved: (value) {
// make a copy of contact for every attribute change
contact = Contact(id: contact.id, name: value);
}
),
....
],
),
),
...
OR here I use contact without final keyword, and changing property directly in the object, without make a copy.... changing object state.
...
Contact contact;
@override
void initState() {
// load from database
contact = Provider.of<ContactProvider>(context, listen: false).findContactExample();
super.initState();
}
...
Form(
key: _form,
child: ListView(
children: <Widget>[
....
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
initialValue: contact.name,
onSaved: (value) {
// changing object state
contact.name = value;
}
),
// .... there are many field
],
),
),
...
Aucun commentaire:
Enregistrer un commentaire