Widget Lifecycle Events
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.
To build the UI, you use two main types of widgets, StatelessWidget and StatefulWidget. A stateless widget is used when the values (state) do not change, and the stateful widget is used when values (state) change.
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, and when an InheritedWidget has changed.
The following sample code shows a StatelessWidget base structure, and Figure 1.1 displays the widget’s lifecycle
class JournalList 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.
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.
class JournalEdit extends StatefulWidget {
const JournalEdit({Key? key}) : super(key: key);
@override
State<JournalEdit> createState() => _JournalEditState();
}
class _JournalEditState extends State<JournalEdit> {
@override
Widget build(BuildContext context) {
return Container();
}
}
You can override different portions of the StatefulWidget to customize and manipulate data at different points of the widget lifecycle. Table 1.1 shows some of the stateful widget main overrides, and the majority of the time you’ll use the initState(), didChangeDependencies(), and dispose() methods. You’ll use the build() method all of the time to build your UI.




Comments
Post a Comment