I'm currently learning Flutter. I tried to deep dive into Flutter Widget life-cycle, and I wonder why StatefulWidget
are written like this :
class Example extends StatefulWidget {
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
// initState
// setState
// ...
@override
Widget build(BuildContext build) {
...
}
}
but not :
class Example extends StatefulWidget {
// initState
// setState
// ...
@override
Widget build(BuildContext build) {
...
}
}
I think the latter makes the source simple. But I don't know why they're using the former style ?
Why is the build method on State, and not StatefulWidget? Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.
The build method is called any time you call setState , your widget's dependencies update, or any of the parent widgets are rebuilt (when setState is called inside of those).
build method Null safetyDescribes the part of the user interface represented by this widget. The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes).
Is initState called before build? initState() This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. It must also call super.
The reason why StatefulWidget
uses a separate State
class and not having build
method inside its body is because all fields inside a Widget
are immutable, and this includes all its sub-classes.
You might have noticed that StatelessWidget
has its build
and other associated methods defined inside it, but that was possible due to the nature of StatelessWidget
which is rendered completely using the provided info, and doesn't expect any future change in its State
.
In the case of StatefulWidget
, State
information occasionally change (or expected to change) during the course of the app, thus this information isn't suitable for storage in a final field (build
) to satisfy Widget
class conditions (all fields are immutable). That's why State
class is introduced. You just have to override the createState
function to attach your defined State
to your StatefulWidget
, and let all that change happens in a separate class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With