Search code examples
flutterradio-buttonflutter-layout

How to set a radio button checked by default in Flutter?


By default Flutter shows all the radio buttons empty (unchecked).

How to set a radio button checked by default?

I'm posting this question to document my solution, that may help some one, and also start a topic about this, because I didn't find anything about it here.

Below the radio button code:

class _ProductTypeScreen extends State<ProductType> {

  String _radioValue; //Initial definition of radio button value
  String choice;

  void radioButtonChanges(String value) {
    setState(() {
      _radioValue = value;
      switch (value) {
        case 'one':
          choice = value;
          break;
        case 'two':
          choice = value;
          break;
        case 'three':
          choice = value;
          break;
        default:
          choice = null;
      }
      debugPrint(choice); //Debug the choice in console
    });
  }

  // Now in the BuildContext... body widget:

  @override
  Widget build(BuildContext context) {
  //First of the three radio buttons

  Row(
    children: <Widget>[
      Radio(
        value: 'one',
        groupValue: _radioValue,
        onChanged: radioButtonChanges,
      ),
      Text(
        "One selected",
      ),
    ],
  ),

Solution

  • add an initial state

    class _ProductTypeScreen extends State<ProductType> {
    
      String _radioValue; //Initial definition of radio button value
      String choice;
    
      // ------ [add the next block] ------ 
      @override
      void initState() {
        setState(() {
          _radioValue = "one";
        });
        super.initState();
      }
      // ------ end: [add the next block] ------  
    
      void radioButtonChanges(String value) {
        setState(() {
          _radioValue = value;
          switch (value) {
            case 'one':
              choice = value;
              break;
            case 'two':
              choice = value;
              break;
            case 'three':
              choice = value;
              break;
            default:
              choice = null;
          }
          debugPrint(choice); //Debug the choice in console
        });
      }
    
      @override
      Widget build(BuildContext context) {