Flutter Provider 重新初始化模型 [英] Flutter Provider reinitialize model
问题描述
我使用 MultiProvider,然后创建我的所有模型.延迟加载已启用,因此当我打开我的页面小部件时,当我调用 Provider.of<>(context) 时会调用我的模型的构造函数.
I use MultiProvider and then create all my models. Lazy loading is enabled and as such when I open my page widget the constructor of my model is called when I call Provider.of<>(context).
这会初始化我的模型,模型会获得新数据.
This initialize my model and the model gets fresh data.
然而,我有以下问题,当我弹出视图(小部件)并稍后重新访问视图(小部件)时,再次调用 Provider.of<>(context),但由于模型已经初始化我从模型中获取以前的数据(这很有用,因为我确实使用它来保留某些屏幕之间的状态).
I have the following issue however, when I pop the view(widget) and revisit the view(widget) later, Provider.of<>(context) is called again, but since the model was already initialized I get the previous data from the model (This is useful because I do use this to preserve state between certain screens).
我需要重新初始化我的模型,因为我需要刷新我的数据并重置页面值,并且由于永远不会再次调用构造函数,我没有得到任何这些.
I need my model to reinitialize since I need to refresh my data and reset the page values, and since the constructor is never called again, I don't get any of these.
无论我做什么,如果我从 initState()/didChangeDependencies() 调用 initialize 方法,它总是会出错,因为我在小部件时更改数据正在建设中.
No matter what I do, if I call the initialize method from initState() / didChangeDependencies() it always error since I'm changing the data while the widget is building.
我正在寻找类似以下内容:
I'm looking for something like the following:
MyChangeNotifier variable = MyChangeNotifier();
ChangeNotifierProvider.value(
value: variable,
child: child()
)
重新初始化我的班级,但从我读到的内容来看,这很糟糕,不知道在哪里调用它.
To reinitialize my class, but from what I read this is bad and don't know where to call it.
我不知道如何继续,任何帮助将不胜感激.
I have no idea how to proceed and any help would be appreciated.
推荐答案
所以我在 Provider 的实际文档中找到了我想要的东西 此处.
So I found what I was looking for in the Provider actual documentation here.
关键是调用将更新 UI 或触发 Future.microTask() 内部重建的代码.这只会在未来完成后触发重建,而不会在小部件树仍在构建时触发重建.
The key is to call your code that would update the UI or trigger a rebuild inside a Future.microTask(). This will only then trigger the rebuild once the future completes and not trigger the rebuild while the widget tree is still building.
@override
initState() {
super.initState();
Future.microtask(() =>
context.read<MyNotifier>(context).getMyData(); // Or in my situation initialize the page.
);
}
这篇关于Flutter Provider 重新初始化模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!