【问题标题】:Override dispose method in a ChangeNotifier覆盖 ChangeNotifier 中的 dispose 方法
【发布时间】:2020-04-22 05:51:54
【问题描述】:

我有以下型号

class SelectorModel with ChangeNotifier {
    .... // stuff relating to the model
}

在我的模型中,我使用以下内容获取 Firestore 文档流:

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
  });

我需要一种方法来处理 _subsciption,这样当我的 Firestore 数据库中发生更改时,当我的模型已经被处理时,它就不会尝试调用 callingMethod()

我正在寻找的是一种类似于以下 ChangeNotifier 的方法:

@override
void dispose() {
    super.dispose();
    _subscription.cancel();
}

我查看了提供商docs,但找不到任何东西。

感谢您的帮助!

【问题讨论】:

  • 我不明白。您是否在问题中发布了解决方案?您给出的dispose 示例是可行且正确的解决方案。
  • @RémiRousselet,你是​​对的,但由于某种原因,我仍然收到错误:[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: A SelectJobModel was used after being处置。 E/flutter (5628):一旦你在 SelectJobModel 上调用了 dispose(),它就不能再使用了。
  • 这是一个不同的问题。您给出的dispose 示例是正确的,那么您需要修复其他错误
  • @RémiRousselet 我有一个问题,我正在从ChangeNotifier 覆盖dispose 函数中关闭我的_stremController。它会自动关闭_streamController 还是?我正在使用Provider

标签: flutter flutter-provider


【解决方案1】:

如果我理解你,你可以这样做

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
   _subscription.cancel();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多