首页 > 解决方案 > 如何显示来自 ChangeNotifier 模型的对话框

问题描述

在我的项目中,当ChangeNotifier类收到状态时,它会设置一个布尔值并调用notifyListeners(). 在我的主要build()功能中,然后我检查挂起的布尔值并相应地显示对话框 - 但我只能通过在构建方法中给它一个小的延迟来显示对话框 - 似乎缺少上下文。


TL;博士:

有没有办法在ChangeNotifier课堂上显示对话框?

标签: flutterflutter-change-notifier

解决方案


即使你可以通过传递 a 来做到这一点BuildContext,你也不应该这样做,因为你只会将你的情况耦合ChangeNotifier到特定的情况。

假设这是您的模型:

class Model extends ChangeNotifier {
  bool _loading = false;

  bool get loading => _loading;

  void update(bool value) {
    _loading = value;
    notifyListeners();
  }
}

并且说,您正在loading使用以下按钮更新值:

final model = Provider.of<Model>(context, listen: false);
model.update(true);

您应该在此处自己执行逻辑,或者您可能正在项目中的其他地方收听此模型:

final model = Provider.of<Model>(context);

然后,您应该通过检查来显示对话框:

if (model.loading) {
  // show dialog
}

推荐阅读