Search code examples
flutterflutter-provider

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


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.


Solution

  • 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 achieved 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: ...,
    );