It shows an error on the setstate in flutter but wrote correctly. Kindly help to rectify it.
error on setstate
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.white,
),
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key}) : super(key: key);
var naveen = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("hello"),
),
body: Center(
child: Column(
children: [
TextButton(onPressed: (){
setState((){
naveen++;
print(naveen);
});
}, child: Text('button')),
Text("$naveen")
],
),
),
);
}
}
It shows an error on the setstate in flutter but wrote correctly. Kindly help to rectify it.
2
Answers
You should use
StatefulWidget
to usesetState
.Your
MyHomePage
should be like..setState is a method that is available only in stateful widgets in Flutter. Stateless widgets are immutable and don’t have any internal state, so you cannot call setState in them.
If you want to update the state of a widget, you should use a stateful widget instead. In a stateful widget, you can define a state object that holds the mutable state of the widget. You can then use the setState method to update the state, which triggers a rebuild of the widget.
If you have already created a stateless widget and you want to convert it into a stateful widget, you can do the following:
Create a new class that extends StatefulWidget.
Move the code of your stateless widget into the build method of the
new class.
Create a new class that extends State and use it to hold the mutable
state of the widget.
Override the createState method in your new stateful widget class
and return an instance of the state class you just created.
Update your widget tree to use the new stateful widget instead of
the old stateless widget.