为什么在 setstate 函数调用 flutter 后我的文本没有改变

why isn't my text doesn't change after the setstate function is call flutter

大家好,我有一些问题。 为什么在按下按钮并调用 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,控制器,但错误仍然存​​在

更改这行代码,

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) {
     ...

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

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

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