gpt4 book ai didi

flutter - 如何从 ChangeNotifier 模型显示对话框

转载 作者:行者123 更新时间:2023-12-04 09:57:39 31 4
gpt4 key购买 nike

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

TL;博士:

有什么方法可以从 ChangeNotifier 中显示对话框类(class)?

最佳答案

即使你可以通过传递 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
}

关于flutter - 如何从 ChangeNotifier 模型显示对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61891242/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com