flutter 中的 initState 和 super.initState 是什么?

What is initState and super.initState in flutter?

文档里有写,但我看不懂。

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then the State should subscribe to that object during initState, unsubscribe from the old object and subscribe to the new object when it changes in didUpdateWidget, and then unsubscribe from the object in dispose.

You cannot use BuildContext.inheritFromWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.inheritFromWidgetOfExactType can be used there.

If you override this, make sure your method starts with a call to super.initState().

但我不确定它的含义。能解释一下吗?

归功于@Remi,initState() 是一种方法,当有状态的小部件被插入到小部件树中时,它会被调用一次。

如果我们需要进行某种初始化工作(例如注册侦听器),我们通常会覆盖此方法,因为与 build() 不同,此方法只调用一次。

要取消注册您的侦听器(或做一些 post 工作),您需要覆盖 dispose() 方法。


来自here

A subclass of State can override initState to do work that needs to happen just once. For example, override initState to configure animations or to subscribe to platform services. Implementations of initState are required to start by calling super.initState

When a state object is no longer needed, the framework calls dispose() on the state object. Override the dispose function to do cleanup work. For example, override dispose to cancel timers or to unsubscribe from platform services. Implementations of dispose typically end by calling super.dispose

initState()的使用

initState()是classState的一个方法,被认为是Flutter中重要的生命周期方法。 initState() 仅调用一次,我们将其用于一次性初始化。

示例:

  • 初始化依赖于具体BuildContext的数据。

  • 初始化需要在build()之前执行的数据。

  • 订阅Streams.

谢谢你的回答,但我也会重申一下上面的人的状态

@overrride
initState() {         // this is called when the class is initialized or called for the first time
  super.initState();  //  this is the material super constructor for init state to link your instance initState to the global initState context
}