没有为Flutter中的类MyApp错误定义方法'setState'

esu*_*esu 11 flutter

我正在错误The method 'setState' isn't defined for the class MyApp error in FlutteronSubmittedTextField

码:

  Widget build(BuildContext context) {

    String phoneNo;

    return new MaterialApp(
      title: 'SchoolTrack',
      theme: new ThemeData(
        primaryColor: Colors.grey[50],
      ),
      home: new Scaffold(
        appBar: null,

        backgroundColor: Colors.cyan[100],

        body: new Container(

          padding: const EdgeInsets.all(32.0),
          child: new Center(
            child: new TextField(
              autofocus: true,
              autocorrect: false,


              decoration: new InputDecoration(
                  hintText: 'Type the phone no',
                  suffixIcon: new Icon(Icons.send),
                  suffixStyle: new TextStyle(
                    color: Colors.cyan[300],
                  )
              ),

                onSubmitted: (String input) {
                  setState(() {
                    phoneNo = input;
                  });
                },

            ),
          ),
        ),
      )
    );
   }
Run Code Online (Sandbox Code Playgroud)

L.8*_*885 13

地方

设置状态

里面

有状态的小部件

:) 这将解决问题


Ous*_*ush 11

我假设您正在尝试在无状态小部件中设置setState,这是不可变的(无法更改)。

使用有状态的小部件来这样做,如下所示:

class MainPage extends StatefulWidget{
  HomePage createState()=> HomePage();
}

class HomePage extends State<MainPage>{
 //Your code here
}
Run Code Online (Sandbox Code Playgroud)


Col*_*tar 9

您必须在有状态小部件中调用该函数


Cop*_*oad 9

setState仅在类/子类内部可用StatefulWidget。您需要将您的转换StatelessWidgetStatefulWidget. 简单地:

单击该类StatelessWidget并使用option+ return(如果您在 macOS 上使用 VS Code,则使用cmd+ ),.

在此输入图像描述


Oma*_*sam 7

确保您输入正确

setState( () {} ) ;
Run Code Online (Sandbox Code Playgroud)