如何从没有上下文的类访问提供者字段? [英] How to access to provider field from class that do not have context?
问题描述
我正在使用Provider
.我有两个类:class TenderApiData {}
它是独立类(不是小部件).如何将accesstoken
写入AppState
?
I am using Provider
. I have got two classes: class TenderApiData {}
it's stand alone class (not widget). How I can write accesstoken
to AppState
?
class AppState extends ChangeNotifier // putted to ChangeNotifierProvider
{
String _accesstoken; // need to fill not from widget but from stand alone class
String _customer; // Fill from widget
List<String> _regions; // Fill from widget
List<String> _industry; // Fill from widget
...
}
我需要从独立的类中读取/写入accesstoken
的方法.
I need way to read\write accesstoken
from stand alone classes.
还是我的应用程序体系结构有问题?
Or I have issue with architecture of my app?
此处是完整的源代码.
推荐答案
您不能也不应访问窗口小部件树之外的提供程序.
You cannot and should not access providers outside of the widget tree.
即使您理论上可以使用全局变量/单例或get_it
之类的替代方法,也不要这样做.
Even if you could theoretically use globals/singletons or an alternative like get_it
, don't do that.
您将改为使用小部件在提供程序和模型之间架起桥梁.
You will instead want to use a widget to do the bridge between your provider, and your model.
这通常是通过didChangeDependencies
生命周期归档的,就像这样:
This is usually archived through the didChangeDependencies
life-cycle, like so:
class MyState extends State<T> {
MyModel model = MyModel();
@override
void didChangeDependencies() {
super.didChangeDependencies();
model.valueThatComesFromAProvider = Provider.of<MyDependency>(context);
}
}
provider
带有一个小部件内置小部件,这些小部件可帮助解决常见情况,即:
provider
comes with a widget built-in widgets that help with common scenarios, that are:
-
ProxyProvider
-
ChangeNotifierProxyProvider
ProxyProvider
ChangeNotifierProxyProvider
一个典型的例子是:
ChangeNotifierProxyProvider<TenderApiData, AppState>(
initialBuilder: () => AppState(),
builder: (_, tender, model) => model
..accessToken = tender.accessToken,
child: ...,
);
这篇关于如何从没有上下文的类访问提供者字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!