Middle
What is the lifecycle of a Stateful widget in Flutter?
sobes.tech AI
Answer from AI
createState(): Creates aStateobject for the widget.initState(): Initializes the state, subscribes to streams, animations. Called once when the widget is created.didChangeDependencies(): Called afterinitState()and when dependencies change (e.g., InheritedWidget).build(): Builds the user interface. Called during initialization and when the state changes (setState()).didUpdateWidget(): Called when the widget's configuration is updated by the parent widget.setState(): Notifies the framework of internal state changes, leading to a rebuild (build).deactivate(): Called when theStateis removed from the widget tree (can happen temporarily, e.g., when switching tabs).dispose(): Cleans up resources: unsubscribes from streams, disposes animation controllers. Called before theStateis permanently removed from memory.
// Example of using setState to show state change
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;
@override
void initState() {
super.initState();
// Initialization
// print('initState');
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Dependencies changed
// print('didChangeDependencies');
}
@override
void didUpdateWidget(MyStatefulWidget oldWidget) {
super.didUpdateWidget(oldWidget);
// Widget updated
// print('didUpdateWidget');
}
void _incrementCounter() {
setState(() {
// Change state, triggers rebuild
_counter++;
// print('setState: counter = $_counter');
});
}
@override
Widget build(BuildContext context) {
// Build UI
// print('build');
return Scaffold(
appBar: AppBar(
title: Text('Counter Example'),
),
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),
),
);
}
@override
void deactivate() {
super.deactivate();
// Widget deactivated
// print('deactivate');
}
@override
void dispose() {
// Resource cleanup
// print('dispose');
super.dispose();
}
}