Checking widget tree for a BLoC

Checking widget tree for a BLoC

This checks if a BLoC is in the widget tree, so you can call methods on it, kinda weird to be doing it but...

I have come across this a couple of times, when BLoCs are being reused. Not very common and I bet there is a nicer way to solve this but keeping it as a snippet just in case it comes up again.

1TheCubit? theCubit;
2final hasTheCubit = context.findAncestorWidgetOfExactType<
3    BlocProvider<TheCubit>>();
4if (hasTheCubit != null) {
5  theCubit = context.read<TheCubit>();
6}
7  if (theCubit != null) {
8    theCubit.methodOnCubit(param);
9  }
10