Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method 'setState' isn't defined for the class MyApp error in Flutter

Tags:

flutter

I am getting the error The method 'setState' isn't defined for the class MyApp error in Flutter in the onSubmitted of the TextField

Code:

  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;
                  });
                },

            ),
          ),
        ),
      )
    );
   }
like image 704
esu Avatar asked Apr 01 '18 10:04

esu


People also ask

How do you define setState in flutter?

Whenever you change the internal state of a State object, make the change in a function that you pass to setState: setState(() { _myState = newValue; }); The provided callback is immediately called synchronously.

What is StatefulBuilder flutter?

Overview. The StatefulBuilder widget makes it possible to rebuild only certain small regions when the states of those regions change without much effort. That improves the performance of the application.

How do I create a stateful widget?

To create a stateful widget in a flutter, use the createState() method. The stateful widget is the widget that describes part of a user interface by building a constellation of other widgets that represent a user interface more concretely. A stateful Widget means a widget that has a mutable state.


3 Answers

I assume you are trying to setState in a stateless widget, which is immutable(unable to change).

Use a stateful widget to do so, like this:

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

class HomePage extends State<MainPage>{
 //Your code here
}
like image 60
Oush Avatar answered Oct 16 '22 14:10

Oush


place

setState

inside

StatefullWidget

:) that will solve the problem

like image 15
L.885 Avatar answered Oct 16 '22 15:10

L.885


You have to call that function within a stateful widget

like image 12
Coldstar Avatar answered Oct 16 '22 14:10

Coldstar