Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createState method not always called when creating new StatefulWidget

Tags:

flutter

dart

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,
  );
}
like image 659
Miki Avatar asked Nov 12 '18 00:11

Miki


People also ask

Which method of stateful widget notifies the changes in UI?

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.

What is the lifecycle of a StatefulWidget?

When a Flutter builds a StatefulWidget , it creates a State object. This object is where all the mutable state for that widget is held.

What does createState do in Flutter?

createState method It creates the mutable state for that widget at a given location in the tree.

When should I use stateful widget?

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.


1 Answers

You have to define unique Key for you collections itens, take a look at here: https://www.youtube.com/watch?v=kn0EOS-ZiIc

like image 79
Guilherme Torres Castro Avatar answered Nov 15 '22 11:11

Guilherme Torres Castro