I am using Bloc in my app, I want to call certain Functions inside a cubit when the back button is pressed.
This is the Widget.
PopScope(
canPop: false,
onPopInvoked: (bool val) async {
back();
},
child: MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => ChatCubit(
locator(),
locator(),
),
),
BlocProvider(
create: (context) => IsTypingCubit(
),
),
],
child: child...
this is the back function
void back() {
final emojiController = locator<EmojiController>();
if (emojiController.emojiShowing) {
emojiController.stopShowingEmoji();
} else {
context.read<ChatCubit>().onBackButtonOnChatPage();
context.read<IsTypingCubit>().sendUserStoppedTyping();
}
context.pop();
}
the issue is when the back function is called I get this error
Unhandled Exception: Error: Could not find the correct Provider above this Screen
I added the MultiBlocProvider to the last Widget that this page is called but did not fix this issue.
Obviously, cubits are created further down the tree than you are trying to use them. They should be created above - before function to be available. Something like this:
MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => ChatCubit(
locator(),
locator(),
),
),
BlocProvider(
create: (context) => IsTypingCubit(
),
),
],
....
Builder(
builder: (context) {
return PopScope(
canPop: false,
onPopInvoked: (bool val) async {
back(context);
},