【问题标题】:Should I dispose ValueNotifier object my self? Is it safe to leve it as it is?我应该自己处置 ValueNotifier 对象吗?保持原样安全吗?
【发布时间】:2020-05-30 21:16:13
【问题描述】:

我有一个自定义无状态小部件,它有一个 ValueNotifier 参数作为构造函数参数。

请参阅下面的 sn-p。

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FlatChoiceChipList(
      choiceList: ["first item","second item","third item"],
      selectedIndex: ValueNotifier<int>(0),
      onSelected: (index) {},
    );
  }
}

嗯,正如你在上面的sn-p中看到的,在build方法中我创建了一个ValueNotifier对象,以后没有dispose它。

  1. 在构建方法中创建 ValueNotifier 是否安全?
  2. 我应该在父 Stateful Widget 中创建 ValueNotifier 并在父 Stateful Widget 被释放时自行释放它吗??

【问题讨论】:

    标签: flutter flutter-widget


    【解决方案1】:

    1.如果你愿意,你可以,但你为什么不在你的 FlatChoiceChipList 小部件中声明它?

    2.我相信只有在你添加监听器的情况下。这是 dispose 方法:

    @mustCallSuper
    void dispose() {
      assert(_debugAssertNotDisposed());
      _listeners = null;
    }
    

    但是,当您不再需要它时,最好将其丢弃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多