【发布时间】:2021-08-16 06:43:01
【问题描述】:
大家好,我有一些问题。 为什么按下按钮并调用 setstate 后我的文本没有改变。
这是我的代码
class noname extends StatefulWidget {
const noname({Key? key}) : super(key: key);
@override
_nonameState createState() => _nonameState();
}
class _nonameState extends State<noname> {
@override
Widget build(BuildContext context) {
String newtext = 'hello ';
final TextEditingController descriptioncontroller = TextEditingController();
final formKey = GlobalKey<FormState>();
return Scaffold(
body: Column(children: [
Form(
key: formKey,
child: Column(children: [
TextFormField(
controller: descriptioncontroller,
autofocus: true,
validator: (title) {
if (title!.length < 0) {
return 'enter a title ';
} else {
return null;
}
},
decoration: InputDecoration(
border: InputBorder.none,
labelText: 'input your title ',
),
),
])),
ElevatedButton(onPressed: () {
setState(() {
newtext = descriptioncontroller.text;
});
print('your user input is ' + descriptioncontroller.text);
}, child: Text('saved')),
Text(newtext)
]),
);
}
}
我已经尝试 onchange,控制器,但错误仍然存在
【问题讨论】:
-
嘿!你知道调用 setState 会发生什么吗?
-
它只是再次构建了 UI!因此,它再次运行构建函数。
-
以及每次调用您的构建函数时。 newtext 变量变为等于 'hello' 。因此,只需将变量声明出来。在initState方法中初始化变量就完成了!
-
哦,好的,谢谢您的帮助。我现在明白为什么了