How to Add Radio Button in Flutter

Radio buttons are a good way to take inputs from users. They allow users only to choose one option from a group. In this blog post, let’s see how to add a radio button in flutter.

If you are looking for how to add a checkbox in flutter then you can go here.

We use Radio widget from flutter to add radio buttons. Using Radio widget with ListTile widget helps us to create a neat radio button with label.

    ListTile(
      title: const Text('Lafayette'),
      leading: Radio(
        value: 'lafayette',
        groupValue: _character,
        onChanged: (value) {
          setState(() {
            _character = value;
          });
        },
      ),
    ),

As you noticed, we need a stateful widget to make the radio buttons work. When the groupValue is changed using setState, the radio button gets updated. Hence the selected value is reflected as groupValue. Following is the complete example of radio buttons in flutter.

import 'package:flutter/material.dart';
void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Radio Button Example',
      home: RadioButtonExample(),
    );
  }
}

class RadioButtonExample extends StatefulWidget {
  RadioButtonExample({Key key}) : super(key: key);
  
  @override
  _RadioButtonExampleState createState() => _RadioButtonExampleState();
}

class _RadioButtonExampleState extends State<RadioButtonExample> {

  var selectedValue = 'animal';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
    body:Container(
       child: Padding(
         padding: const EdgeInsets.all(10.0),
         child:Column(
    children: <Widget>[
      ListTile(
        title: const Text('Giraffe'),
        leading: Radio(
          value: 'animal',
          groupValue: selectedValue,
          onChanged: (value) {
            setState(() { selectedValue = value; });
          },
        ),
      ),
      ListTile(
        title: const Text('Penguin'),
        leading: Radio(
          value: 'bird',
          groupValue: selectedValue,
          onChanged: (value) {
            setState(() { selectedValue = value; });
          },
        ),
      ),
    ],
  )
    ),),);
  }
}

Following is the output of this flutter radio button example.

I hope you liked this flutter tutorial. Stay tuned for more tutorials.

1 thought on “How to Add Radio Button in Flutter”

  1. Pingback: How to Add Dropdown Menu in Flutter – Flutter For You

Leave a Comment

Your email address will not be published. Required fields are marked *