How to use BlocBuilder to refresh a Dialog in Flutter
Asked Answered
G

2

8

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.

Gervais answered 26/12, 2021 at 6:15 Comment(3)
please share your CustomDialog code.Warily
please share Example Cubit and Example State and Custom Dialog . Current Information is not EnoughHammons
the problem is that the builder of BlocBuilder doesn't recall when it is in builder of show dialog and my cubit and state don't matter.Gervais
S
26

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.

Shoemake answered 28/12, 2021 at 7:24 Comment(0)
A
0

Maybe you, like me, are trying to get an array in the state, but when you update your array, you don't do it like that

newArray = [... oldArray]
Actinal answered 15/8 at 19:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.