createState method not always called when creating new StatefulWidget

Viewed 2678

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,
  );
}
1 Answers
Related