Search code examples
flutterradio-buttonflutter-layout

How do I make a Radio Widget look like a button


Im rebuilding an old app and need to make radio buttons look like actual buttons. Whats the best way to do this?

Old app reference:


Solution

  • You can use a stateful widget and keep track of a selected value in that widget. The widget will be a container, with child Text. When tapped you change the selected value. Then based on the selected value you return a different BoxDecoration for your container. See Below for code:

    class ButtonStyleRadioButton extends StatefulWidget {
     // Function to call when tapped
     Function(bool) onChanged;
    
     ButtonStyleRadioButton({this.onChanged});
    
    _ButtonStyleRadioButtonState createState() => _ButtonStyleRadioButtonState();
    }
    
    class _ButtonStyleRadioButtonState extends State<ButtonStyleRadioButton> {
      bool _selected = false;
    
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: (){ setState(() {
           _selected = !_selected; 
           // Callback to passed in function
           widget.onChanged(_selected);
          });},
          child: Container(
          padding: EdgeInsets.all(10.0),
          child:  Text('Consumer'),
           decoration: BoxDecoration(
             borderRadius: BorderRadius.circular(50.0),
             border: Border.all(color: Colors.grey[400]),
             color: _selected ? Colors.red : Colors.white
           )));
      }
    }