Search code examples
flutterbloccubit

Check if a cubit is in the context


is there a way to check if a cubit/bloc is available in the current context. I have a widget which is used in different pages/widgets, an some of the pages are using a cubit, but not all.

I need the state of the cubit, but only if a cubit is available.

if (context.read<MyCubit>().state) {

The context.read method throws an error when the cubit is not available.

So what I need is a method to check if a cubit is in the context.


Solution

  • using

    Provider.of<MyCubit?>(context)
    

    will return null if MyCubit does not exist in the context