About the usage of initState() and setState() in flutter

  1. initState()Functions are executed before the component is rendered. In Flutter, initState()is StatefulWidgetone of the lifecycle methods, which build()is called before calling the method.
  2. When one is created StatefulWidgetand added to the component tree, Flutter instantiates the component's state object and initState()calls build()method after method to build the UI.
  3. 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.
  4. 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 it initState()in.
  5. 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 use Future, , async/awaitetc. to handle them.
  6. setState()Method does not trigger initState()re-execution. When called setState(), it notifies the Flutter framework to rebuild the related component tree and call build()methods to update the UI.
  7. 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.
  8. When you call setState()the method, Flutter will detect that the state has changed and execute build()the method associated with the component to generate a new UI. In build()the method, you can use the new state value for UI rendering.
  9. So, when you setState()update the state data in Flutter, Flutter will rebuild the related components, but will not re-execute initState()the method. initState()Will only be called once when the component is initially created.

Guess you like

Origin blog.csdn.net/DongShanYuXiao/article/details/132501191