Flutter using bloc in showDialog not working

32 views Asked by At

I am using Bloc and want to access a cubit within a showDialog-Widget.

I read that I have to pass the correct context, since showDialog creates its own.

I tried it like this:

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CouponCodeCubit(
        onSuccess: onSuccess,
        request: request,
      ),
      child: Builder(
        builder: (cubitContext) {
          return Center(
            child: UISecondaryButton(
              title: UILocalization.parentsAddChildDetailsButtonCoupon(),
              onTap: () {

                showDialog(
                  context: cubitContext,
                  builder: (_) {
                    return StatefulBuilder(
                      builder: (_, setState) {
                        return _Dialog(
                          cubitContext: cubitContext,
                          initialValue: initialValue ?? '',
                          focusNode: foucsNode,
                          onRemoveCoupon: onRemoveCoupon,
                        );
                      },
                    );
                  },
                );
              },
            ),
          );
        },
      ),
    );
  }
}

But when I call final couponCodeCubit = widget.cubitContext.watch<CouponCodeCubit>(); inside my _Dialog it fails with:

Exception has occurred. ProviderNotFoundException (Error: Could not find the correct Provider<CouponCodeCubit> above this Builder Widget

This happens because you used a BuildContext that does not include the provider of your choice. There are a few common scenarios:

  • You added a new provider in your main.dart and performed a hot-reload. To fix, perform a hot-restart.

  • The provider you are trying to read is in a different route.

...

I even tried wrapping it with a StatefulBuilder as suggested here.

But nothing is working. I also tried passing the Cubit, but this won't update _Dialog when state changes.

What am I misisng here? How can I solve this? Let me know if you need any more info.

0

There are 0 answers