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