gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:40:00 26 4
gpt4 key购买 nike

在文档中是这样写的,但我无法理解。

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() 不同,这个方法只被调用一次。

要取消注册你的监听器(或做一些后期工作),你重写 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

关于flutter - Flutter 中的 initState 和 super.initState 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com