initState()
Functions are executed before the component is rendered. In Flutter,initState()
isStatefulWidget
one of the lifecycle methods, whichbuild()
is called before calling the method.- When one is created
StatefulWidget
and added to the component tree, Flutter instantiates the component's state object andinitState()
callsbuild()
method after method to build the UI. initState()
It is usually used to perform some initialization operations, such as data acquisition, subscribing to events, starting timers, etc. It will only be called once, and only once during the entire life of the component.- Once
initState()
called and complete,build()
the method is called immediately to build the UI. So, if you want to perform some operations before the UI is built, you can put itinitState()
in. - It is worth noting that
initState()
you do not perform time-consuming operations or operations that block the UI thread in , as this may cause the application to freeze. If you need to perform asynchronous operations, you can useFuture
, ,async/await
etc. to handle them. setState()
Method does not triggerinitState()
re-execution. When calledsetState()
, it notifies the Flutter framework to rebuild the related component tree and callbuild()
methods to update the UI.initState()
The method is only called once when the component is initialized, and will not be executed again during the entire life cycle of the component. It is mainly used to perform some initialization operations, such as data acquisition, subscribing to events, starting timers, etc.- When you call
setState()
the method, Flutter will detect that the state has changed and executebuild()
the method associated with the component to generate a new UI. Inbuild()
the method, you can use the new state value for UI rendering. - So, when you
setState()
update the state data in Flutter, Flutter will rebuild the related components, but will not re-executeinitState()
the method.initState()
Will only be called once when the component is initially created.
About the usage of initState() and setState() in flutter
Guess you like
Origin blog.csdn.net/DongShanYuXiao/article/details/132501191
Ranking