Junior — Middle
Explain the lifecycle stages of the widget component during its usage and deactivation.
sobes.tech AI
Answer from AI
The widget lifecycle in Flutter includes several stages:
- Create: The widget's constructor is called, and its instance is created.
- Initialize state (initState): Called on StatefulWidget, where data and subscriptions can be initialized.
- Build: Called to render the widget on the screen, can be called multiple times when the state changes.
- Update (didUpdateWidget): Called when the parent widget updates and passes new parameters.
- Deactivate: Called before removing the widget from the tree, resources can be released.
- Dispose: Called when the widget is permanently removed, subscriptions, timers should be canceled, and controllers cleaned up.
Example usage:
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() {
// Resource cleanup
super.dispose();
}
}