Flutter Radio is commonly used to select options like gender (male/female), etc. below we have used two cases which commonly used in flutter applications
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selectedRadio = 0;
setSelectedRadio(int val) {
setState(() {
selectedRadio = val;
});
}
List<String> items = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
String selectedOption = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Radio Button Example'),
),
body: Column(
children: [
// Case1
RadioListTile(
value: 0,
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val!);
},
title: Text('Radio 1'),
),
RadioListTile(
value: 1,
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val!);
},
title: Text('Radio 2'),
),
RadioListTile(
value: 2,
groupValue: selectedRadio,
onChanged: (val) {
setSelectedRadio(val!);
},
title: Text('Radio 3'),
),
SizedBox(height: 16.0),
Text('Selected Radio>>>>>: $selectedRadio'),
//case2
for (String item in items)
RadioListTile<String>(
title: Text(item),
value: item,
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
),
SizedBox(height: 20),
Text('Selected Option: $selectedOption', style: TextStyle(fontSize: 16)),
],
),
);
}
}