Flutter Error

Solve the method ‘setState’ isn’t defined for the class MyApp error in Flutter

You can solve the error The method 'setState' isn't defined for the class MyApp error in Flutter by simply creating your own StatefulWidget widget. The main reason whey you might be encountering such error in your project is that, you’re calling 'setState' in a stateless widget or in a method that does not build stateful-Widget.

Flutter “setState” isn’t defined for class error example.

Take a good look at below code and you will see that within the block of the onSubmitted method TextField() widget we’re calling ‘setState’. It will surely throw an error because the setState method needs to be called only in a widget that can rebuild itself but stateless widget can’t. Stateless widget is immutable and because of that they can not be changed and we’re forcing to rebuild it in below code and guess what will happen, an error.

class MyApp extends StatelessWidget {
  const MyApp ({ super.key });

  @override
  Widget build(BuildContext context) {

    String phoneNumber;

    return new MaterialApp(
      title: 'My Application',
      theme: new ThemeData(
        primaryColor: Colors.red,
      ),
      home: new Scaffold(
        appBar: null,

        backgroundColor: Colors.black,

        body: Container(

          padding: const EdgeInsets.all(30.0),
          child: new Center(
            child: new TextField(
              autofocus: true,
              autocorrect: false,
              decoration: new InputDecoration(
                  hintText: 'Type the phone number here',
                  suffixIcon: new Icon(Icons.send),
                  suffixStyle: new TextStyle(
                    color: Colors.cyan[300],
                  )
              ),

                onSubmitted: (String phnNumber) {
                // this will cause The method 'setState' isn't defined for the class MyApp error
                // because we’re inside a stateless widget
                  setState(() {
                    phoneNumber = phnNumber;
                  });
                },

            ),
          ),
        ),
      )
    );
   }
}

The simple way to solve the above bug is to convert your class to a stateful widget like below:

class HomeScreen extends StatefulWidget{
  HomeActivity createState()=> HomeActivity ();
}

class HomeActivity extends State< HomeScreen >{
 //Your code goes here
}

But to be able to manipulate it and take full advantage of Stateful widget, we need to understand what it means. So let quickly explore what and how it different from stateless widget.

What is Stateful widget in flutter?

It simply a widget that represent part of the user interface/UI by building a constellation of other widgets that predict the user interface more concretely. The building process continues recursively in other words repeatedly until the description of the user interface is fully concrete or accurate. Below image shows what Google Flutter teams says about it in the Flutter docs:

What is stateful widget in flutter?

Example and skeleton of stateful widget subclass named MyApp.

class MyApp extends StatefulWidget {
  const MyApp({ Key? key }) : super(key: key);

  @override
  State createState() => _MyAppState();
}

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return Center(child:Text(“My first flutter app”));
  }
}

The format or code snippet of stateful widget looks like below:

class HomeScreen extends StatefulWidget{
  HomeActivity createState()=> HomeActivity ();
}

class HomeActivity extends State< HomeScreen >{
 //Your code goes here
}

Whenever you change a state object it will not reflect until you change the internal state as well. You have to call setState or pass the change as an argument to it function.

setState(() {_myState = new_Value; });

Now let come back to the main point. So with the little understand of the difference between the two widget, we can resolve the above question like this:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

 @override
  Widget build(BuildContext context) {

    String phoneNumber;

    return new MaterialApp(
      title: 'My Application',
      theme: new ThemeData(
        primaryColor: Colors.red,
      ),
      home: new Scaffold(
        appBar: null,

        backgroundColor: Colors.black,

        body: Container(

          padding: const EdgeInsets.all(30.0),
          child: new Center(
            child: new TextField(
              autofocus: true,
              autocorrect: false,
              decoration: new InputDecoration(
                  hintText: 'Type the phone number here',
                  suffixIcon: new Icon(Icons.send),
                  suffixStyle: new TextStyle(
                    color: Colors.cyan[300],
                  )
              ),

                onSubmitted: (String phnNumber) {
                // this will cause The method 'setState' isn't defined for the class MyApp error
                // because we’re inside a stateless widget
                  setState(() {
                    phoneNumber = phnNumber;
                  });
                },

            ),
          ),
        ),
      )
    );
   }
}

Solution: setState{} is only needed to rebuild an object state in a subclass/class of a Stateful Widget. So the only thing we did above the fix the bug was to simple convert our class from stateless to statefulWidget.

How to convert widget to statefulWidget?

Click to select or highlet the StatelessWidget class name and hit option + return or cmd + .  This will only work if you use VS Code on macOS for android studio, you need a different command.

Related Posts

disable back button flutter

Override Or Disable Back Button Flutter Appbar – The Easy Way

Learn how to override/disable back button pressed in flutter applications to make your app standout from the rest. Why because, whiles users are interacting with your app, they…

flutter-error-setstate-called-after-dispose

Flutter error: setState() called after dispose()

When building apps with Flutter framework you will often encounter this common error “Unhandled Exception: setState() called after dispose() or during build.” This exception is related to something…

disable back button flutter

How to Shift Focus to Next TextField in Flutter

Learn how to shift focus to the next TextField or TextFormField in flutter applications. The whole idea is that when you’re done typing text in one TextField, we…

working with list in Dart/Flutter

Null check operator used on a null value – flutter

The “Null check operator used on a null value” error occurs in flutter apps when you unintentionally access a variable that has a null value. For example, if…