How to read Riverpod provider outside Widget tree

75 Views Asked by At

This is an ecommerce based app. Im maintaining a map of products viewed by user using provider. When app moves to background, I want to access the provider and make a network call to update the values.

I tried to use provider container


final globalProviderContainer = ProviderContainer();
@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      
      final views = globalProviderContainer.read(
        viewsCounterNotifierProvider,
      );
      print(views);
      performBackgroundAction();
    }

This only returns empty value for the data.

1

There are 1 best solutions below

2
Aizan Sagheer On

You need to add the following line in initState

WidgetsBinding.instance.addObserver(this);

Then do like this:

  @override
     void didChangeAppLifecycleState(AppLifecycleState state) {
     super.didChangeAppLifecycleState(state);
     final views = globalProviderContainer.read(
    viewsCounterNotifierProvider,
  );
  print(views);
  performBackgroundAction();
 }

The other option you can adopt is to use isolate like

void backgroundTask() {
  final globalProviderContainer = ProviderContainer();
final views = globalProviderContainer.read(
    viewsCounterNotifierProvider,
  );
  print(views);
  performBackgroundAction();

}

and then call this in isolate

@override
     void didChangeAppLifecycleState(AppLifecycleState state) {
     super.didChangeAppLifecycleState(state);
     FlutterIsolate.spawn(backgroundTask);
}

To use isolate, use flutter_isolate package