简体   繁体   English

Flutter 提供程序重新初始化 model

[英]Flutter Provider reinitialize model

I use MultiProvider and then create all my models.我使用 MultiProvider,然后创建我所有的模型。 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) .延迟加载已启用,因此当我打开我的页面小部件时,我的 model 的构造函数在我调用Provider.of<>(context)时被调用。

This initialize my model and the model gets fresh data.这将初始化我的 model 和 model 获取新数据。

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).但是我有以下问题,当我弹出视图(小部件)并稍后重新访问视图(小部件)时, Provider.of<>(context)再次被调用,但由于 model 已经初始化,我从model(这很有用,因为我确实使用它来在某些屏幕之间保留 state)。

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.我需要我的 model 重新初始化,因为我需要刷新我的数据并重置页面值,并且由于构造函数不再被调用,我没有得到任何这些。

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.无论我做什么,如果我从initState() / didChangeDependencies()调用初始化方法,它总是会出错,因为我在构建小部件时更改了数据。

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.重新初始化我的 class,但从我读到的内容来看,这很糟糕,不知道在哪里调用它。

I have no idea how to proceed and any help would be appreciated.我不知道如何进行,任何帮助将不胜感激。

So I found what I was looking for in the Provider actual documentation here .所以我在这里的 Provider 实际文档中找到了我想要的东西。

The key is to call your code that would update the UI or trigger a rebuild inside a Future.microTask().关键是调用您的代码来更新 UI 或在 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.
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM