Life Cycle of Stateless and Stateful Widgets in Flutter
Sep 18, 2024
--
Understanding the life cycle of widgets is key to effective Flutter development. This post summarizes the life cycles of stateless and stateful widgets.
Stateless Widgets
Stateless widgets are immutable and suitable for static content. Their life cycle is simple:
- Creation: Instantiated via the constructor.
- Build Method: The
build
method is called to render the widget (once unless the parent rebuilds). - Destruction: Automatically disposed of when removed from the widget tree
Stateful Widgets
Stateful widgets can change over time. Their life cycle includes:
- Creation: Widget is instantiated.
- State Initialization:
createState
creates the state object. - Build Method: The state’s
build
method renders the widget. - State Changes:
setState
triggers a rebuild to reflect updates.
Key Lifecycle Methods:
initState()
: Initialization.didChangeDependencies()
: Called on dependency changes.build()
: Renders UI.dispose()
: Cleans up resources.