如何从没有上下文的类访问提供者字段? [英] How to access to provider field from class that do not have context?

查看:84
本文介绍了如何从没有上下文的类访问提供者字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆