Widget Life Cycle In Flutter

Widget Life Cycle In Flutter

Flutter has two types of widgets Stateless Widget, and Stateful Widget.

Stateless Widget:

  • Stateless Widgets are rendered only once when the widget is loaded. We can't rebuild a Stateless widget based on any user events or changes.

Stateful Widgets:

  • Stateful Widgets can be rebuilt and have their own Widget Lifecycle to create, update and destroy the widgets.

  • In Flutter, widgets have several lifecycle methods that the framework calls during different stages of their lifecycle. Here are the most important ones:

  • createState(): This method is called during the construction stage of a stateful widget and creates a corresponding state object.

  • initState(): This method is called during the initialization stage of stateful widget and is used to initialize any resources the widget needs.

  • didChangeDependencies(): This method is called during the dependencies resolution stage of a widget, and is used to handle any changes to the widget's dependencies.

  • build(): This method is called during the build stage of a widget and is used to build and render the widget.

  • setState(): This method is called when the state of a Stateful widget changes, and triggers a rebuild of the widget.

  • deactivate(): This method is called when a widget is removed from the widget tree and is used to release any resources the widget no longer needs.

  • dispose(): This method is called when a widget is permanently removed from the widget tree and is used to release any resources the widget is holding.

  • These methods can be overridden in custom widget classes to provide custom behavior during different stages of the widget lifecycle.

  • For example, you can use the initState() method to initialize controllers or listeners, the build() method to construct and render the widget's UI, and the setState() method to update the state of a Stateful widget, prompting a rebuild of the widget tree.

Happy Coding!! 🙂

Did you find this article valuable?

Support Flutter Blogs by becoming a sponsor. Any amount is appreciated!