How to have access Context in didChangeAppLifecycleState lifecycle hook using flutter HookWidget?

Viewed 1401

I'm trying to access context so i can read my provider but since this lifecycle hook is out side the widget tree. it's not accessible. is there a way to get access to context?

5 Answers

I researched a little bit and finally discussed with narcodico from the flutter bloc community, so the credits are for him.

Therefore, mixin WidgetsBindingObserver on a state class, the context is available even in the overrides like didChangeAppLifecycleState since they are part of the state class.

Also, take in consideration to move to BlocProvider above the state widget.

Example

class HomePageProvider extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<InAppPurchasesBloc>(),
      child: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
...
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      context
          .read<InAppPurchasesBloc>()
          .add(const InAppPurchasesEvent.getPurchaserInfo());
    }
  }
...
}

I am afraid you can't access context inside didChangeAppLifecycleState.

For anyone interested, you can save your scaffold state in a global key, and access the context from its current state.

You may consider using the Riverpod package instead of Provider. Riverpod is from the same author as Provider and considered the "better Provider", but with many improvements including Flutter independence, meaning it does not rely on a context to work, and you can use it almost the same way as provider.

Using Riverpod, along with Flutter Hooks, you can do something like:

// create a provider in a global context
final myProvider = Provider((ref) => myClass());

// access the provider inside your class
class MyWidget extends HookWidget{

  //access the provider using a hook
  final myClassProvider = useProvider(myProvider);
  //... your logic
  @override
  Widget build (BuildContext context){/* ... build widget tree... */}
}

Consider this very useful and concise tutorial with how to use Riverpod with Flutter Hooks and StateNotifier, ChangeNotifier, etc...

Related