Junior — Middle
Explain the lifecycle stages of StatefulWidget in Flutter.
sobes.tech AI
Answer from AI
The lifecycle of a StatefulWidget in Flutter consists of several key stages:
- Creating the StatefulWidget — the widget's constructor is called.
- Creating the State — the
createState()method creates a state object that holds mutable data. - Initializing the state — the
initState()method is called, where initial setup can be performed. - Building the UI — the
build()method is called to render the widget on the screen. - Updating the state — calling
setState()triggers a rebuild viabuild(). - Handling updates — the
didUpdateWidget()method is called if the widget is updated with new parameters. - Cleaning up resources — the
dispose()method is called when the widget is removed, to free resources.
Example:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
@override
void initState() {
super.initState();
// Initialization
}
@override
Widget build(BuildContext context) {
return Container();
}
@override
void dispose() {
// Cleanup
super.dispose();
}
}