Earlier, we have been through various articles based on dismiss dialog In a Flutter. So this time, we will go with How to Solve The Method ‘setState’ isn’t Defined For the Class MyApp Error In Flutter?
Solve The Method ‘setState’ isn’t Defined For the Class MyApp Error In Flutter?
What is Stateful Widget?
It’s a Flutter widget that describes the user interface by simply building the constellation of other widgets that describe the user interface more accurately. The building process of this widget continues recursively until the widget gets an accurate user interface description.
Example:
This is an skeleton of stateful widget subclass named YellowBird.
class YellowBird extends StatefulWidget {
const YellowBird({ Key? key }) : super(key: key);
@override
State createState() => _YellowBirdState();
}
class _YellowBirdState extends State {
@override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}
In a Stateful Widget it will have a code snippet like the below:
class MainPage extends StatefulWidget{
HomePage createState()=> HomePage();
}
class HomePage extends State<MainPage>{
//Your code here
}
Whenever you change the internal state of a State object, make the change in a function that you pass to setState:
setState(() { _myState = newValue; });
Resolve the above question, like this:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
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;
});
},
),
),
),
)
);
}
}
setState{} is only available inside a Stateful Widget class/subclass. You need to convert your Stateless Widget to a StatefulWidget. Simply:
Output
Method ‘setState’ isn’t Defined For the Class MyApp Error
Click on the StatelessWidget class and use option + return or cmd + . if you use VS Code on macOS.
Conclusion:
Thanks for Reading !!!
In this article, We have been through How to Solve The Method ‘setState’ isn’t Defined For the Class MyApp Error In Flutter ??
Keep Learning !!! Keep Fluttering !!!
Flutter Agency is dedicated to Flutter technology, and Flutter development issue solutions. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc. If you need to hire dedicated Flutter Developer feel free to contact Flutter Agency.
Article source: https://flutteragency.com/solve-the-method-setstate-isnt-defined-for-class-myapp-error/