I have a collection of simple objets that sometimes changes. I am using a ListView to render those objects, basically text. When my collection changes the list is rebuild with the new objects, so if the list changes from 1 to 3 items, I see 3 items, but the first one keeps its previous value.
I've noticed that the method "createState" is not called in all cases when I create a new CustomTextField (in the example above, it is called only when new elements are added to the list).
How do I make sure my list is updated properly when my collection changes?
My parent widget builds a list of text fields:
...
@override
Widget build(BuildContext context) {
...
var list = <Widget>[];
collection.forEach((item) {
var widget = CustomTextField(
content: item,
);
list.add(widget);
...
return new ListView(
children: list,
);
});
...
My CustomTextField definition:
class CustomTextField extends StatefulWidget {
final MediaContent content;
CustomTextField({
Key key,
this.content,
}) : super(key: key);
@override
CustomTextFieldState createState() {
return CustomTextFieldState();
}
}
...
MediaContent is a very simple object containing some text:
class MediaContent {
String textData;
ContentType type;
MediaContent(
this.type,
);
}
A stateful widget is implemented by two classes: a subclass of StatefulWidget and a subclass of State . The state class contains the widget's mutable state and the widget's build() method. When the widget's state changes, the state object calls setState() , telling the framework to redraw the widget.
When a Flutter builds a StatefulWidget , it creates a State object. This object is where all the mutable state for that widget is held.
createState method It creates the mutable state for that widget at a given location in the tree.
Stateful widgets are useful when the part of the user interface you are describing can change dynamically, e.g. due to having an internal clock-driven state, or depending on some system state.
You have to define unique Key for you collections itens, take a look at here: https://www.youtube.com/watch?v=kn0EOS-ZiIc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With