How to access to provider field from class that do not have context?

烂漫一生 提交于 2020-01-14 06:52:06

问题


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

I need way to read\write accesstoken from stand alone classes.

Or I have issue with architecture of my app?

Here is full source code.


回答1:


You cannot and should not access providers outside of the widget tree.

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.

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 comes with a widget built-in widgets that help with common scenarios, that are:

  • ProxyProvider
  • ChangeNotifierProxyProvider

A typical example would be:

ChangeNotifierProxyProvider<TenderApiData, AppState>(
  initialBuilder: () => AppState(),
  builder: (_, tender, model) => model
    ..accessToken = tender.accessToken,
  child: ...,
);


来源:https://stackoverflow.com/questions/57415617/how-to-access-to-provider-field-from-class-that-do-not-have-context

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