Flutter StatefulWidget

Flutter StatefulWidget Tutorial and Examples

In this piece we want to look at a widget from which you will be deriving in almost any real world flutter projects you will create, the StatefulWidget.

What is StatefulWidget?

A StatefulWidget is a widget that has mutable state.

Technically it’s an abstract class and is one of the classes that directly derive from the also abstract Widget class.

abstract class StatefulWidget extends Widget

It’s defined in the flutter package:

It’s unique feature is the fact it has mutable state while it’s sister the StatelessWidget doesn’t.

Basically the State refers to information that

  1. can be read synchronously when the widget is built.
  2. might change during the lifetime of the widget.

Stateful widgets will describe part of a user interface by building a constellation of other widgets that describe the user interface more concretely. The building process continues recursively until the description of the user interface is fully concrete (e.g., consists entirely of RenderObjectWidgets, which describe concrete RenderObjects).

These widgets(Stateful) are important when the part of the user interface you are describing can change dynamically.

If you are creating interfaces that rely only on the configuration information in the object itself and the BuildContext in which the widget is inflated, consider using StatelessWidget.

StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method, or in objects to which that State subscribes.

The framework will call createState whenever it inflates a StatefulWidget, which means that multiple State objects might be associated with the same StatefulWidget if that widget has been inserted into the tree in multiple places. Similarly, if a StatefulWidget is removed from the tree and later inserted in to the tree again, the framework will call createState again to create a fresh State object, simplifying the lifecycle of State objects.

A StatefulWidget keeps the same State object when moving from one location in the tree to another if its creator used a GlobalKey for its key.


Share an Example

Share an Example

What is the capital of Egypt? ( Cairo )