1

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.

A.K.
  • 568
  • 5
  • 17
  • I don't know a neat way to do that.What about writing a separate function and wrapping ```context.read().state``` inside a ```try catch ``` clause ? return false when an ```Exception``` occures. – Xoltawn May 20 '22 at 16:38
  • Yeah, it's possible to do that with try catch, but i that a clean solution. – A.K. May 20 '22 at 16:43
  • 1
    Does this help? https://stackoverflow.com/questions/68369060/how-can-i-check-to-see-if-provided-class-exists – Xoltawn May 20 '22 at 16:53

1 Answers1

1

using

Provider.of<MyCubit?>(context)

will return null if MyCubit does not exist in the context

Xoltawn
  • 1,445
  • 1
  • 11
  • 17