Junior — Middle
What is the sequence of method calls in the lifecycle of a State object?
sobes.tech AI
Answer from AI
The lifecycle of a State object in Flutter includes the following main methods, called in a specific sequence:
- constructor — an instance of State is created.
- initState() — called once when the State is initialized, usually to initialize data and subscribe to streams.
- didChangeDependencies() — called immediately after initState and when dependencies change, for example, if an InheritedWidget changes.
- build() — called every time the widget needs to be rendered, for example, after setState.
- didUpdateWidget() — called if the parent widget changes and the state needs to be updated.
- setState() — manually called to update the state and trigger a rebuild.
- deactivate() — called when the State is temporarily removed from the widget tree.
- dispose() — called when the State is permanently removed, to free resources.
An example of a simplified lifecycle:
class MyWidgetState extends State<MyWidget> {
@override
void initState() {
super.initState();
// initialization
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// respond to dependency changes
}
@override
Widget build(BuildContext context) {
return Container();
}
@override
void dispose() {
// free resources
super.dispose();
}
}