6

I have a dialog and I wrap it in a blocbuilder to update it according to the type of state but the dialog just is built First time and after state has changed it doesn't rebuild.

showDialog(
  context: context,
  builder: (_) {
  BlocBuilder<ExampleCubit, ExampleState>(
      bloc: cubit,
      builder: (context, state) {
        return CustomDialog(
          title:"title",
          onSave: (File file) {
            cubit.uploadImage(file);
          },
          progress: (state is ExtendedExampleState)? state.progress:0,
          onDelete: () {},
          onCancel: () {
             cubit.cancelUploading();
          },
        );
      },
    );

Note: It is important to use Bloc pattern rather StateFulBuilder.

Parisa Baastani
  • 1,713
  • 14
  • 31

1 Answers1

15

You can use BlocBuilder in Dialog so that it gets rebuilt every time there's a change. For that to work, you also need to pass the current cubit(bloc) using BlocProvider.value.

  // Get the cubit(bloc) instance
  final exampleCubit = context.read<ExampleCubit>();

  showDialog(
    context: context,
    builder: (BuildContext context) {
      // Provide the existing cubit(bloc) instance to the new route (the dialog)
      return BlocProvider<ExampleCubit>.value(
        value: exampleCubit,
        child: CustomDialog(
            //... your implementation
        ),
      );
    },
  );
  

And now, make sure that you're using BlocBuilder in CustomDialog, like so:

class CustomDialog extends StatelessWidget {

  const CustomDialog({
    Key? key,  
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ExampleCubit, ExampleState>(
      builder: (context, state) {
        // rebuild widget...
      }
    )
  }

With this setup, the dialog gets updated using bloc.

Michal Šrůtek
  • 1,647
  • 16
  • 17