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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)