Aly Eldin Muhammad
Aly Eldin Muhammad

Reputation: 31

Why is flutter bloc v8 closing a globally created cubit when I pop some screen that was using this cubit

it gives me this error:

Unhandled Exception: Bad state: Cannot add new events after calling close.

Upvotes: 3

Views: 1150

Answers (1)

RandomSlav
RandomSlav

Reputation: 602

Maybe I'm a bit late but my guess is that you used

BlocProvider<ExistingCubit>(
  create: (_) => ExistingCubit(),
)

to pass existing cubit to new page.

You should instead use

BlocProvider.value(
 value: context.read<ExistingCubit>()
)

As the docs say

BlocProvider.value Takes a [value] and a [child] which will have access to the [value] via BlocProvider.of(context). When BlocProvider.value is used, the [Bloc] or [Cubit] will not be automatically closed. As a result, BlocProvider.value should only be used for providing existing instances to new subtrees. A new [Bloc] or [Cubit] should not be created in BlocProvider.value. New instances should always be created using the default constructor within the [Create] function.

Upvotes: 5

Related Questions