flutter - 如何显示来自 ChangeNotifier 模型的对话框
问题描述
在我的项目中,当ChangeNotifier
类收到状态时,它会设置一个布尔值并调用notifyListeners()
. 在我的主要build()
功能中,然后我检查挂起的布尔值并相应地显示对话框 - 但我只能通过在构建方法中给它一个小的延迟来显示对话框 - 似乎缺少上下文。
TL;博士:
有没有办法在ChangeNotifier
课堂上显示对话框?
解决方案
即使你可以通过传递 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
}
推荐阅读
- python - 将 html 附加到电子邮件时,“NoneType”对象没有属性“编码”错误
- ruby-on-rails - 在 Minikube 中调试 Rails 应用程序
- r - 为什么 R 中双精度变量 NA 的范围是多少,如何将其更改为整数?
- css - 将css样式导入故事书时找不到global.css
- oracle - 使用 plsql 进行回归编程以获得完美匹配
- css - 如何制作两个高度相同的方块?
- elasticsearch - 使用弹性搜索的关键字搜索
- scala - 如何在 Flink 中使用多个计数器
- javascript - for循环javascript中的异步函数
- python - 如何从 csv 文件中读取行并使用 Python 代码将其存储在数组中?