Instead of looking at something specific, let’s take a step back today and revert to one of the basics in Flutter. A brief overview of Stateful widgets in Flutter!

Stateless vs. Stateful

Before we take a look at Stateful widgets, we have to take a look at its counterpart: the Stateless widget. The naming should already give most of it away, but how does it look in practice?

Stateless widgets are, yes, stateless. You basically draw your widget once, and that’s it. It’s not made to change in any way, but rather just simply show how you defined it. Default examples of a Stateless widget could be Text or Container.

Stateful widgets, however, are dynamic. In short, this means that the widget might contain a property that can change, triggering your UI (widget) to update. Let’s take a checkbox, for example, containing 2 states: true or false/checked or unchecked. We’ll keep track of its state in a property: isChecked. Let’s assume the checkbox starts off in the unchecked state. By tapping it, we’ll update the isChecked property and update the UI accordingly. Since the isChecked property can change and the UI changes with it, the widget is dynamic, hence: Stateful!

Since Stateful widgets are dynamic, they’re more expensive to use as opposed to Stateless widgets. Always take this into account when wanting to convert a Stateless widget to a Stateful one!

Creating a Stateful widget

Unlike a Stateless widget, creating a Stateful widget requires 2 classes: the widget itself and its State. The widget itself won’t do much apart from actually creating the state through createState(). You could initialize some properties through the constructor, but most work will be done in the State class. The dynamic properties we described earlier will be put and updated here for example, but most importantly: the State class is where we actually build our widget tree.

#flutter

Flutter’s Stateful Widget cheat sheet
8.45 GEEK