A Flutter widget is said to be stateful if it has a mutable state that can change over time. More accurately, a widget is stateful when it defines
a piece of user interface that may change appearance or behavior over time. Such changes of appearance or behavior are modelled into variations of the
internal state of the widget.
The state defined in a stateful Flutter widget is ephemeral,
meaning that it is not persistent and is not to be shared between different instances of the same widget.
This is because in most cases, the state of a widget is local and doesn’t need to be accessed by other widgets in the components tree. Therefore,
the Flutter framework can make simplifying assumptions on the lifecycle of such a state, incapsulating it in the StatefulWidget
class,
that exposes the createState
method.
The createState
method is called by the framework whenever a new instance of the widget is created, and should only create a new state
object.
import 'package:flutter/widgets/framework.dart';
class MyState extends State<MyStatefulWidget> {
int i1 = 42;
MyState() { }
}
class MyStatefulWidget extends StatefulWidget {
@override
MyState createState() => MyState();
}
What is the potential impact?
Doing more than creating a new instance in the createState
method can lead to unexpected behavior. For example, if a state object is
cached in a top-level variable and reused across multiple instances of the same widget, a change in the state of one instance will affect all other
instances sharing the same state object.