gpt4 book ai didi

flutter - 即使在 setState 之后,复选标记也不会显示在 flutter 复选框上

转载 作者:IT王子 更新时间:2023-10-29 06:57:49 24 4
gpt4 key购买 nike

    Widget build(BuildContext context) {
// TODO: implement build
var TaskTextField;
var _newValue = false;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("To-Do List V2 R1"),
),
body: Container(
child: Column(
children: <Widget>[
Container(
child: TextField(
decoration:
InputDecoration(hintText: "Enter task to be added"),
onChanged: (taskTextField) {
TaskTextField = taskTextField;
print(TaskTextField);
},
),
margin: EdgeInsets.all(16.0),
),
Text("Click Me!"),
Checkbox(
activeColor: Colors.blue,
value: _newValue,
onChanged: (val) {
setState(() {
_newValue = !_newValue;
});
},
),
],
),
),
),
);
}
}

即使调试器在单击时显示 _newValue 为真,复选标记也不会显示。我尝试了不同的方法,例如使用_newValue = !_newValue 但它仍然不起作用。我在 Flutter 1.2.1 上运行。

最佳答案

每次执行函数时,都会重新创建在函数/方法内声明的变量。 setState() 导致 build() 重新运行,因此 _newValue 每次都被初始化为 false

将字段移出build()方法以保留值

var _newValue = false;

Widget build(BuildContext context) {
// TODO: implement build
var TaskTextField;
...

关于flutter - 即使在 setState 之后,复选标记也不会显示在 flutter 复选框上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com