Understanding the use of StatefulWidget in Flutter Understanding the use of StatefulWidget in Flutter dart dart

Understanding the use of StatefulWidget in Flutter


The "outer class" is final, every widget is final (immutable). This means that all its properties have to be final as well:

class RandomWords extends StatefulWidget {  final String name;  @override  createState() => new RandomWordsState();}class RandomWordsState extends State<RandomWords> {  String name;  @override  void initState() {    name = widget.name;    super.initState();  }  @override  Widget build(BuildContext context) => Text(name);  void someMethod() {    print(widget.name);    setState(() => name = 'new name');  }}

From the State all fields of the StatefulWidget can be accessed and obviously not changed because they are final.

State's, however, can change data. setState will execute its callback and then rebuild the State (with the new data).

StatelessWidget's can also be rebuilt, i.e. when its parent is rebuilding, but all state is lost and no data is kept. That is what State's are being used for.


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> {@overrideWidget 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.


From what I understand, it's to save information about the widget. So you implement setState everytime you want to save a variable or something. See the tutorial about adding interactivity in Flutter.