Flutter Provider reinitialize model

流过昼夜 提交于 2021-01-29 09:29:50

问题


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.

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.

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.


回答1:


So I found what I was looking for in the Provider actual documentation here.

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.
  );
}


来源:https://stackoverflow.com/questions/61799239/flutter-provider-reinitialize-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!