尽管sputter调用build(并打印如下所示的正确信息),但它似乎没有构建新的TaskWidgets(不调用TaskWidgetState的构造函数中的print)。这在我的应用程序中创建了一些不寻常的行为(例如,删除的ListView项的持久性)。
我有以下代码:
class TaskWidget extends StatefulWidget {
TaskWidget({this.task, this.callToSave, this.callToDelete});
final Task task;
final Function callToSave;
final Function callToDelete;
@override
State<StatefulWidget> createState() {
return new TaskWidgetState(task, callToSave, callToDelete);
}
}
class TaskWidgetState extends State<TaskWidget>{
Task task;
Function toCallOnChange;
Function callToDelete;
TaskWidgetState(Task task, Function callToSave, Function callToDelete){
print("I'm a task widget for " + task.serialise().toString());
this.task = task;
toCallOnChange = callToSave;
this.callToDelete = callToDelete;
}
}
和
class ToDoListWidget extends State<ToDoList>{
List<Task> _toDo = new List<Task>();
...
@override
Widget build(BuildContext context) {
print("building");
return new Scaffold(
body: new ListView(
children: <Widget> [
generateCard(),
...
]
),
);
}
Widget generateCard() {
return new Card(
child: new Column (
children: generateWidgets()
),
...
);
}
List<Widget> generateWidgets() {
print("generating Widgets");
List<Task> tasks = getTasks();
List<Widget> widgets = new List<Widget>();
print("I have " + tasks.length.toString() + " widgets to build");
for(Task t in tasks) {
print(t.title);
TaskWidget widget = new TaskWidget(task: t, callToSave: saveList, callToDelete: deleteTask,);
widgets.add(widget);
}
return widgets;
}
}
打印出来:
建筑
I / flutter(28783):每日回归 I / flutter(28783)://正确,未删除任务
但屏幕状态并未反映此
答案 0 :(得分:1)
您未正确使用State
和Stateful Widget
。
它如何在颤动中起作用是可以多次创建窗口小部件,但很可能只有一个State
的实例可以与它一起使用。
拥有一个州的构造函数是一种反模式。
相反,你应该做这样的事情:
class TaskWidget extends StatefulWidget {
TaskWidget({this.task, this.callToSave, this.callToDelete});
final Task task;
final Function callToSave;
final Function callToDelete;
@override
State<StatefulWidget> createState() => new TaskWidgetState();
}
class TaskWidgetState extends State<TaskWidget>{
Widget build(Context context) {
// you can just use the widget.task, this is to illustrate.
var task = widget.task;
var callToSave = widget.callToSave;
var callToDelete = widget.calltoDelete;
}
}
这样,当widget
发生更改时,您的状态将会重新构建,并将使用传递给窗口小部件的更新值。