How Flutter Handle State in StatefulWidget?¶
Flutter's state management within StatefulWidget is an essential part of how the framework creates responsive and interactive user interfaces. Here's a detailed overview of how Flutter keeps track of the states in StatefulWidget:
How Flutter Keeps Track of States¶
- Elements and Widgets:
- Flutter uses a combination of
Widgets,Elements, andStateobjects to manage the lifecycle and rendering of UI components -
For a
StatefulWidget, Flutter creates an associatedStateobject that holds the mutable state for the widget -
Widget Lifecycle:
- When a
StatefulWidgetis inserted into the widget tree, Flutter creates aStateobject by calling the widget'screateStatemethod -
The
Stateobject persists across rebuilds, allowing it to maintain state throughout the widget's lifecycle -
Elements Tree:
- Flutter builds a tree of
Elementobjects that map to the widget tree -
Each
Elementrepresents an instance of a widget in the tree and manages its lifecycle, including the creation, updating, and disposal of associatedStateobjects -
State Object
- The
Stateobject, created by theStatefulWidget, holds all the mutable state for the widget. - The
Stateobject has asetStatemethod that, when called, indicates state changes and triggers a rebuild of the widget
Example: How Flutter Tracks State in a StatefulWidget¶
Here's a simple example to illustrate how Flutter tracks state in a StatefulWidget:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterPage(),
);
}
}
class CounterPage extends StatefulWidget {
@override
_CounterPageState createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Detailed Explanation¶
- Creation:
-
createStateis called when theCounterPagewidget is inserted into the tree, creating an instance of_CounterPageState- Flutter creates an
Elementfor theCounterPagewidget - The
Elementholds a reference to the widget and the associatedStateobject
- Flutter creates an
-
State Initialization:
-
The
_CounterPageStateclass extendsState<CounterPage>and contains the mutable state_counter -
Rendering:
-
Flutter calls the
buildmethod on the_CounterPageStateobject during the rendering phase@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Counter App'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } -
State Update (
setState): -
When the
_incrementCountermethod is called, thesetStatemethod is invoked- The
setStatemethod does the following: - Marks the widget as dirty, indicating that it needs to be rebuilt
- Schedules a new build phase where the
buildmethod is called again with the updated state
- The
-
Rebuild:
- During the build phase, Flutter calls the
buildmethod of_CounterPageStateagain, creating a new widget tree that reflects the updated state (_counter)
Lifecycle Methods in State Class¶
initState: Called when theStateobject is first createddidChangeDependencies: Called when the widget’s dependencies changebuild: Called whenever the widget needs to be rebuiltdidUpdateWidget: Called when the widget is replaced with a new widget of the same typedispose: Called when theStateobject is removed from the tree and will never be rebuilt
Summary¶
- State Management:
- Flutter uses
Stateobjects associated withStatefulWidgets to manage mutable state -
setStateis used to notify the framework of state changes, triggering a rebuild -
Widget Lifecycle:
-
The
Stateobject persists across rebuilds and is managed by theElementtree, maintaining continuity and efficiency -
Reactivity:
- By calling
setState, you ensure that UI components react to changes in state, allowing you to build dynamic and interactive applications
Flutter’s architecture ensures that state management is efficient and intuitive, allowing developers to maintain responsive and fluid user interfaces by using StatefulWidgets and setState effectively.