flutterradio-buttonblocstatelesswidget

Radio button with stateless widget or using BLoC Pattern in Flutter


I need to create a group of radio buttons without using the stateful widget. I want a BLoC Pattern in flutter to create a group of radio buttons. How to create it?

I have only tried using the regular Radio widget using the onChange state management.


Solution

  • Please try to post some code in the future, so we can help you figure out what is wrong with the code itself or the approach. I'm not sure if this is precisely what you are asking for, but you can create stateless widget, which will act as radio buttons group using BLOC library.

    Let's say you have 2 options (for radio buttons):

    enum RadioButtonOption {
      FirstOption,
      SecondOption;
    }
    

    and to simplify things, we will create simplest Cubit possible, to manipulate state of radio buttons group:

    class RadioCubit extends Cubit<RadioButtonOption> {
      RadioCubit(RadioButtonOption initialOption) : super(initialOption);
    
      void changeOption(RadioButtonOption newOption) {
        emit(newOption);
      }
    }
    

    To make it work in the stateless widget, you need to create the cubit and whenever the onChanged function is invoked, just pass the result to the cubit. Using BlocBuilder will automatically update the UI:

    class MyHomePage extends StatelessWidget {
      const MyHomePage({super.key});
    
      void changeOption(RadioButtonOption? newValue, BuildContext context) {
        if (newValue != null) {
          context.read<RadioCubit>().changeOption(newValue);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: BlocProvider(
            create: (_) => RadioCubit(RadioButtonOption.FirstOption),
            child: BlocBuilder<RadioCubit, RadioButtonOption>(
              builder: (context, state) {
                return Column(
                  children: [
                    Radio(
                      value: RadioButtonOption.FirstOption,
                      groupValue: state,
                      onChanged: (newValue) {
                        changeOption(newValue, context);
                      },
                    ),
                    Radio(
                      value: RadioButtonOption.SecondOption,
                      groupValue: state,
                      onChanged: (newValue) {
                        changeOption(newValue, context);
                      },
                    ),
                  ],
                );
              },
            ),
          ),
        );
      }
    }
    

    I hope it helps.