Widget Lifecycle
StatefulWidget lifecycle, initState, setState, dispose, didUpdateWidget, build optimization
1Which method is called first when creating a StatefulWidget?
Which method is called first when creating a StatefulWidget?
回答
The createState() method is the first one called when instantiating a StatefulWidget. It creates the State object associated with the widget. This method is automatically called by the Flutter framework when the widget is inserted into the widget tree for the first time.
2What is the correct order of lifecycle methods when a StatefulWidget is created?
What is the correct order of lifecycle methods when a StatefulWidget is created?
回答
The correct order is: createState() creates the State object, then initState() initializes the state, didChangeDependencies() is called after initState and whenever dependencies change, and finally build() constructs the UI. This sequence ensures the state is properly initialized before rendering.
3What is the main purpose of the initState() method?
What is the main purpose of the initState() method?
回答
initState() is used to initialize data that depends on context or to set up listeners, animation controllers and subscriptions. This method is only called once when the State object is created, making it the ideal place for one-time initializations.
Why is it mandatory to call super.initState() in initState()?
What happens when setState() is called in a StatefulWidget?
+17 面接問題