Stateless Widgets:
- Definition: A Stateless widget is immutable, meaning its properties can’t change—all values are final.
- Use Case: Best for simple UI elements that don’t change over time, such as static text, icons, or images.
- Lifecycle: They are built once and do not have a
setState()
method to rebuild themselves.
Example Code for Stateless Widget:
import 'package:flutter/material.dart';
class MyStatelessWidget extends StatelessWidget {
final String title;
const MyStatelessWidget({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text('This is a Stateless Widget'),
),
);
}
}
Stateful Widgets:
- Definition: A Stateful widget can change its state over time and can be redrawn whenever its state changes.
- Use Case: Used for interactive or changing UI elements, like checkboxes, forms, or pages with dynamic content.
- Lifecycle: They have a mutable state object that can use
setState()
to notify the framework that the widget’s state has changed and the widget should be redrawn.
Example Code for Stateful Widget:
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key? key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful Widget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text('$_counter', style: Theme.of(context).textTheme.headline4),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
In summary, the choice between Stateless and Stateful widgets in Flutter depends on whether the widget needs to change over time. For static content, a Stateless widget is sufficient, while interactive or dynamic content requires a Stateful widget.