In Flutter to build the UI, we use two main types of widgets, StatelessWidget and StatefulWidget. The stateful widget is used when the values (state) of a widget changes or has a mutable state that can change over time.
Some important properties of stateful widgets
- A Stateful widget is mutable. It keeps track of the state.
- A Stateful widget’s build() method is called multiple times.
- It rebuilds several times over its lifetime.
Some examples of stateful widgets
Checkbox: Keeps its state whether a checkbox is checked or not.
Radio: Keep its state if it’s selected or not.
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return Container();
}
}
The stateful widget is declared with two classes, the StatefulWidget class and the State class. The StatefulWidget class is rebuilt when the widget’s configuration changes, but the State class can persist (remain).
For example, when the state changes, the widget is rebuilt. If the StatefulWidget is removed from the tree and then inserted back into the tree some time later,then a new State object is created.