【问题标题】:why isn't my text doesn't change after the setstate function is call flutter为什么调用 setstate 函数后我的文本没有改变
【发布时间】: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方法中初始化变量就完成了!
  • 哦,好的,谢谢您的帮助。我现在明白为什么了

标签: flutter dart setstate


【解决方案1】:

更改这行代码,

class _nonameState extends State<noname> {
 @override
 Widget build(BuildContext context) {
  String newtext = 'hello '; // <======== move this up in the class level
 ...

到这里,

    class _nonameState extends State<noname> {
     String newtext = 'hello '; // <======== move it here

     @override
     Widget build(BuildContext context) {
     ...

实际上所有这些都需要是类级别而不是构建功能级别,

   String newtext = 'hello ';
   final TextEditingController descriptioncontroller = TextEditingController();
   final formKey = GlobalKey<FormState>();

【讨论】:

    【解决方案2】:

    你应该只是 String newtext = 'hello '; 移动构建上下文

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2021-05-10
      • 2019-01-06
      • 1970-01-01
      • 2015-10-23
      • 2021-04-01
      • 1970-01-01
      相关资源
      最近更新 更多