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;
});
},
),
),
),
)
);
}
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
}
place
setState
inside
StatefullWidget
:) that will solve the problem
You have to call that function within a stateful widget
Keep the cursor above the 'StatelessWidget' and press Alt + insert and click on 'convert to StatefulWidget', to quickly covert your StatelessWidget to StatefulWidget.
Use a stateful widget to do so
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 to 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;
});
},
),
),
),
)
);
}
}