flutter - Flutter 中的 initState 和 super.initState 是

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

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/

相关文章:

android - 在 Flutter 的登录屏幕中显示循环进度对话框,如何在 Flutter 中实

text - 如果文本溢出,则替换文本

firebase - 如何在 Flutter 中用 Column 或 ListView 类包装 St

dart - Dart AOT 是如何工作的?

visual-studio-code - 带有 VSCode 的 Flutter 显示未安装,即使已

asynchronous - Flutter Redux snackbar

dart - Flutter:主题未应用于文本小部件

dart - 如何将数据发布到 dart 中的 https 服务器?

android - Flutter 按住闪屏 3 秒。如何在 Flutter 中实现闪屏?

android - 错误 : The class 'SingleTickerProviderStat