Search code examples
flutterdartradio-buttonfuture

how to return index radio button value from children Stateful widgets to another stateful widget in Flutter


I need to pass the index value of 2 radio buttons from a children Stateful widgets to another stateful widget in the same page. Then when value is returned, with button Calculate, i will choose between "multiply" or "divide" operation. I already set the if statement, but i cannot get the value from radio buttons. Radio buttons are custom buttons called from main stateful class as MyStatefulWidget().

Code looks like this

class calculator extends StatefulWidget {
const calculator({Key? key}) : super(key: key);

@override
State<calculator> createState() => _calculatorState();
 }

 class _calculatorState extends State<calculator> {

  return Scaffold(
  appBar: AppBar(... some code here....)
     
      ElevatedButton(onPressed: (){
        _showModalBottomSheet(context);
        }, child: Text('Calculate'.toUpperCase(),style: TextStyle(fontWeight: FontWeight.bold),), 
      ),
    ],
  ),
);
}

_showModalBottomSheet(context) {
showModalBottomSheet(context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (BuildContext context){
  return Container(
            child:
            MyStatefulWidget(),
          ),
   ElevatedButton(onPressed: (){
            if (value == 1){
              multiply();
              Navigator.of(context).pop();
              Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => result()));

            }else if (value ==2){
              divide();
              Navigator.of(context).pop();
              Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => result()));
            };

          }, child: Text('Calculate'.toUpperCase(),style: TextStyle(fontWeight: FontWeight.bold),),
            style: ElevatedButton.styleFrom(
                primary: Colors.green),
          ),
        ],

My MyStatefulWidget() class:

class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();}
 
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int value = 0;
Widget CustomRadioButton(String text, int index) {
return OutlinedButton(
  onPressed: () {
    setState(() {
      value = index;
    });
  },
   style: OutlinedButton.styleFrom(
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
    primary: Colors.white,
    backgroundColor: (value == index)?Colors.deepOrange: Colors.white,
  ),
 @override
 Widget build(BuildContext context) {
 return Row(
   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
   children: <Widget>[
     CustomRadioButton("Multiply", 1),
     CustomRadioButton("Divide", 2),
     ],
   );
 }
}

Solution

  • You can pass function callback to MyStatefulWidget and call that function with the index value when the radio button is pressed.

    class MyStatefulWidget extends StatefulWidget {
      final Function(int)? onChanged;
    
      const MyStatefulWidget({
        Key? key,
        this.onChanged,
      }) : super(key: key);
    
      @override
      State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
    }
    

    and now onPressed of the button in your state, you can call this function with the index value

      onPressed: () {
        widget.onChanged?.call(index);
        setState(() {
          value = index;
        });
      }
    

    Finally, pass function to onChanged in MyStatefulWidget

    return Container(child: MyStatefulWidget(onChanged: (value) {
                 // Now you can use this value
               }),
              )