Life Cycle of Flutter Widgets
Stateless Widgets: The widgets which remain constant throughout the lifetime of the app are called stateless widgets. We use them when we want structures to stay the same all over the app, for example, the AppBar, color scheme, i.e. generally the User Interface(UI). These widgets are immutable, i.e. they cannot be changed. Here Hot Reload can reflect the changes made in the app structure and can be used for verification.
Stateless widgets are just like a single block widget that cannot be planned. They can only be destroyed to create a new one with another set of widget configuration and properties.
The life cycle of stateless widgets is simple; there’s only one stage: the build method. As soon as the widget gets built, the build method gets automatically called where you are supposed to create whatever appearance you want to add up in your application.
Stateful Widgets: The widgets used when we want objects to be updated on the screen are called stateful widgets. For example: when a user presses a button to trigger an action ( basically- User Interaction). These widgets are mutable, i.e. they can be manipulated as per the requirements. Here, the Hot Reload cannot reflect the changes made; therefore, to serve the purpose, hot restart is used.
Since stateless widgets can be tracked for their properties and configurations using the state object, we can manage all these variables using the setState() method. The following are the main stages in the lifecycle of a stateful widget:
- init State (): The init State gets triggered implicitly as soon as the State initially get initialized. It is used when we want something to happen the moment our stateful widget is created.
- build (): The build method gets triggered when the widgets are constructed and appear on the screen. It is used when we want something to happen every single time when our stateful widget gets rebuild.
- deactivate(): Deactivate method gets called when the stateful widget gets destroyed ( just like destructor). It is used when we want something to happen just before our stateful widget gets destroyed.