创建新的StatefulWidget时并不总是调用createState方法 [英] createState method not always called when creating new StatefulWidget

查看:231
本文介绍了创建新的StatefulWidget时并不总是调用createState方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收集了一些有时会更改的简单目标.我正在使用ListView渲染那些对象,基本上是文本.当我的集合更改时,该列表将使用新对象进行重建,因此,如果列表从1变为3,我将看到3个项目,但第一个保留其先前的值.

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.

我注意到,当我创建新的CustomTextField时,并非在所有情况下都调用方法"createState"(在上面的示例中,仅当将新元素添加到列表中时才调用该方法).

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,
   );
});
...

我的CustomTextField定义:

My CustomTextField definition:

class CustomTextField extends StatefulWidget {
  final MediaContent content;
  CustomTextField({
    Key key,
    this.content,
  }) : super(key: key);

  @override
  CustomTextFieldState createState() {
    return CustomTextFieldState();
  }
}
...

MediaContent是一个非常简单的对象,其中包含一些文本:

MediaContent is a very simple object containing some text:

class MediaContent {
  String textData;
  ContentType type;

  MediaContent(
    this.type,
  );
}

推荐答案

您必须为您的集合定义唯一的Key,请在此处查看: https://www.youtube.com/watch?v=kn0EOS-ZiIc

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

这篇关于创建新的StatefulWidget时并不总是调用createState方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆