'Best practice: Update Model from View flutter
My question is small and is basically a request for advice on how to follow best practice in flutter. I have years of programming experience, but only a few weeks with flutter or dart.
Scenario: To keep things simple, I have the following:
- Model ClassA which has a List of ClassB. ClassB contains some String properties.
- A StatefulWidget view that has a ClassA instance with a PageView builder based on the List of ClassB
- Every page inside the PageView shows some String properties of ClassB in a TextField
Problem description: Now, I want to update the properties in ClassB in realtime as the user types (or if the focus drops). There's an event for that and I created a method which accepts the ClassB instance. If I change the attribute in that instance, I see no changes to the original list. If I understand it correctly, dart passed the object by value to the event handler and not a reference to the original object. The original object remains unmodified.
In code this would be roughly the following:
Widget createTextField(ClassB classB) {
return EditableText(
onSubmitted: (value) {
setState(() {
classB.myStringValue = value;
});
}
);
}
PageView.builder(
itemBuilder: (BuildContext context, int index) {
var classB = widget.classA.myList[index];
return createTextField(classB);
},
}
)
My approach: Instead of passing the instance of ClassB to the event handler, I just pass the index coming from the builder to the event handler instead. The handler will then directly modify the list inside ClassA using the index.
Now, having a strong Java background this somehow feels weird. My first instinct was to pass the instance of the ClassB to the event handler and modify the instance there. My assumption was that this would be a reference to the original Class B instance.
How would some of you approach this problem? It sounds easy enough, but I just want to follow the best practice here.
Solution 1:[1]
You should wrap the code that changes the value of a property inside
setState((){
// Put your codes here.
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Francis Nduba Numbi |
