Radiobutton in Flutter


import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    title: "Radio Button In Flutter",
    home: Scaffold(
      appBar: AppBar(
        title: Text("Radio Button"),
      ),
      body: MyApp(),
    ),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

enum Gender { Male, Female }

class _MyAppState extends State<MyApp> {
  Gender defaultValue = Gender.Male;
  String gender = "male";

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(height: 10,),
          Text(
            "Radio with ListTile",
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          //Radio Button via ListTile
          ListTile(
            leading: Radio(
              value: Gender.Male,
              groupValue: defaultValue,
              onChanged: (value) {
                setState(() {
                  defaultValue = value;
                  gender = "male";
                });
              },
            ),
            title: Text("Male"),
          ),
          ListTile(
            leading: Radio(
              value: Gender.Female,
              groupValue: defaultValue,
              onChanged: (value) {
                setState(() {
                  defaultValue = value;
                  gender = "female";
                });
              },
            ),
            title: Text("Female"),
          ),
          ElevatedButton(
            onPressed: () {
              print(gender);
            },
            child: Text("Submit Me"),
          ),
          Divider(
            height: 30,
            color: Colors.grey,
          ),
          Text(
            "Radio with RadioListTile",
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          RadioListTile(
            groupValue: defaultValue,
            value: Gender.Male,
            title: Text("Male"),
            selected: true,
            onChanged: (value) {
              setState(() {
                defaultValue = value;
                gender = "male";
              });
            },
          ),
          RadioListTile(
            groupValue: defaultValue,
            value: Gender.Female,
            title: Text("Female"),
            selected: true,
            onChanged: (value) {
              setState(() {
                defaultValue = value;
                gender = "female";
              });
            },
          ),
          ElevatedButton(
            onPressed: () {
              print(gender);
            },
            child: Text("Submit Me"),
          ),
        ],
      ),
    );
  }
}
  

No comments: