FLUTTER WIDGET LIFECYCLE EVENTS
In programming, you have different lifecycle events that usually happen in a linear mode, one after another as each stage is completed. In this section, you’ll learn the widget lifecycle events and their purpose.
The StatelessWidget Lifecycle
A StatelessWidget
is built based on its own configuration and does not change dynamically. For example, the screen displays an image with a description and will not change. The stateless widget is declared with one class. The build
(the UI portions) method of the stateless widget can be called from three different scenarios. It can be called the first time the widget is created when the widget's parent changes.
The following sample code shows a StatelessWidget
base structure, and the image below displays the widget's lifecycle.
class CronativeList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
The StatefulWidget Lifecycle
A StatefulWidget
is built based on its own configuration but can change dynamically. For example, the screen displays an icon with a description, but values can change based on the user's interaction, like choosing a different icon or description. This type of widget has a mutable state that can change over time. 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), enhancing performance. 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 sometime in the future, a new State
object is created. Note that under certain circumstances and restrictions, you can use a GlobalKey
(unique key across the entire app) to reuse (not re‐create) the State
object; however, global keys are expensive, and unless they're needed, you might want to consider not using them. You call the setState()
method to notify the framework that this object has changes, and the widget's build
method is called (scheduled). You would set the new state values inside the setState()
method.
The following example shows a StatefulWidget
base structure, and below image displays the widget's lifecycle. You have two classes, the JournalEdit StatefulWidget
class and the _JournalEditState
class.