What are the main differences between StatefulWidget and StatelessWidget in Flutter?
Shagufta Naz
Top 1% |Freelance Project Manager|B2B Solutions |97% PCR |Content Marketing Expert:Generating Leads & Empowering Freelancers through Valuable Content
The main differences between StatefulWidget and StatelessWidget in Flutter revolve around the ability to manage state:
StatelessWidget
Example:
class MyStatelessWidget extends StatelessWidget {
? @override
? Widget build(BuildContext context) {
??? return Text('I am a StatelessWidget');
? }
}
StatefulWidget
Example:
?
class MyStatefulWidget extends StatefulWidget {
? @override
? MyStatefulWidgetState createState() => MyStatefulWidgetState();
}
?
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
? int _counter = 0;
?
? void _incrementCounter() {
??? setState(() {
????? _counter++;
??? });
? }
?
? @override
? Widget build(BuildContext context) {
??? return Column(
????? children: [
??????? Text('Counter: $_counter'),
??????? ElevatedButton(
????????? onPressed: _incrementCounter,
????????? child: Text('Increment'),
??????? ),
????? ],
??? );
? }
}
Summary
?