如何使用提供程序将ChangeNotifier的作用域限定在某些路由上? [英] How to scope a ChangeNotifier to some routes using Provider?
问题描述
我有一个ChangeNotifier,我想在多条路线之间共享它,但不是所有条路线:
I have a ChangeNotifier, and I would like to share it between multiple routes but not all routes:
Page1是我的第一页.我只需要与Page2,Page3和Page共享ChangeNotifierProvider的数据,并在输入Page1调用后就将ChangeNotifierProvider丢弃.
Page1 is my first page. I need share data of ChangeNotifierProvider with Page2, Page3 and Page only and on enter Page1 call dispose of my ChangeNotifierProvider.
如何使用提供者来做到这一点?
How can I do this using provider?
推荐答案
为此,最简单的解决方案是在每个路由中使用个提供程序,而不是:
To do so, the easiest solution is to have one provider per route, such that instead of:
Provider(
builder: (_) => SomeValue(),
child: MaterialApp(),
)
您有:
final value = SomeValue();
MaterialApp(
routes: {
'/foo': (_) => Provider.value(value: value, child: Foo()),
'/bar': (_) => Provider.value(value: value, child: Bar()),
'/cannot-access-provider': (_) => CannotAccessProvider(),
}
)
另一方面,无法自动处置"您的模型.
It is, on the other hand, not possible to have your model "automatically disposed".
provider
在这种情况下无法知道可以安全处置该对象.
provider
is not able in such a situation to know that it is safe to dispose of the object.
这篇关于如何使用提供程序将ChangeNotifier的作用域限定在某些路由上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!