🎯 Using Radio Buttons and Checkboxes in Flutter
When you're building Flutter apps, you'll often need to let users make choices — like selecting an option from a list or choosing multiple actions. For this, Flutter provides two important widgets:
- Radio buttons – for selecting one option from a group.
- Checkboxes – for selecting one or more options independently.
In this blog post, we'll explore both with simple calculator examples. Each example takes two numbers from the user and performs addition or subtraction based on selected options.
🔘 Example 1: Radio Buttons – One Operation Only
In this example, the user can input two numbers and select either Add or Subtract using radio buttons. Only one can be selected at a time.
👨💻 Dart Code:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: RadioCalculator()));
class RadioCalculator extends StatefulWidget {
@override
_RadioCalculatorState createState() => _RadioCalculatorState();
}
enum Operation { add, subtract }
class _RadioCalculatorState extends State<RadioCalculator> {
TextEditingController _num1Controller = TextEditingController();
TextEditingController _num2Controller = TextEditingController();
Operation? _selectedOperation;
String _result = "";
void _calculate() {
double num1 = double.tryParse(_num1Controller.text) ?? 0;
double num2 = double.tryParse(_num2Controller.text) ?? 0;
if (_selectedOperation == null) {
setState(() {
_result = "Please select an operation.";
});
return;
}
double answer = _selectedOperation == Operation.add
? num1 + num2
: num1 - num2;
setState(() {
_result = "Result: $answer";
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Radio Button Calculator")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _num1Controller,
decoration: InputDecoration(labelText: "Enter first number"),
keyboardType: TextInputType.number,
),
TextField(
controller: _num2Controller,
decoration: InputDecoration(labelText: "Enter second number"),
keyboardType: TextInputType.number,
),
SizedBox(height: 20),
Text("Select an operation:"),
RadioListTile<Operation>(
title: Text("Add"),
value: Operation.add,
groupValue: _selectedOperation,
onChanged: (value) {
setState(() => _selectedOperation = value);
},
),
RadioListTile<Operation>(
title: Text("Subtract"),
value: Operation.subtract,
groupValue: _selectedOperation,
onChanged: (value) {
setState(() => _selectedOperation = value);
},
),
ElevatedButton(
onPressed: _calculate,
child: Text("Calculate"),
),
SizedBox(height: 20),
Text(
_result,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
)
],
),
),
);
}
}
📌 Explanation:
- Uses an
enum Operation
to track selected operation. - Only one
RadioListTile
can be selected at a time. - On clicking "Calculate", the app performs either addition or subtraction.
☑️ Example 2: Checkboxes – Multiple Operations
In this example, the user can select one or both operations using checkboxes. If both are selected, both results are shown.
👨💻 Dart Code:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: CheckboxCalculator()));
class CheckboxCalculator extends StatefulWidget {
@override
_CheckboxCalculatorState createState() => _CheckboxCalculatorState();
}
class _CheckboxCalculatorState extends State<CheckboxCalculator> {
TextEditingController _num1Controller = TextEditingController();
TextEditingController _num2Controller = TextEditingController();
bool _isAdd = false;
bool _isSubtract = false;
String _result = "";
void _calculate() {
double num1 = double.tryParse(_num1Controller.text) ?? 0;
double num2 = double.tryParse(_num2Controller.text) ?? 0;
String output = "";
if (_isAdd) {
output += "Addition: ${num1 + num2}\n";
}
if (_isSubtract) {
output += "Subtraction: ${num1 - num2}\n";
}
if (!_isAdd && !_isSubtract) {
output = "Please select at least one operation.";
}
setState(() {
_result = output;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Checkbox Calculator")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _num1Controller,
decoration: InputDecoration(labelText: "Enter first number"),
keyboardType: TextInputType.number,
),
TextField(
controller: _num2Controller,
decoration: InputDecoration(labelText: "Enter second number"),
keyboardType: TextInputType.number,
),
SizedBox(height: 20),
CheckboxListTile(
title: Text("Add"),
value: _isAdd,
onChanged: (val) {
setState(() => _isAdd = val!);
},
),
CheckboxListTile(
title: Text("Subtract"),
value: _isSubtract,
onChanged: (val) {
setState(() => _isSubtract = val!);
},
),
ElevatedButton(
onPressed: _calculate,
child: Text("Calculate"),
),
SizedBox(height: 20),
Text(
_result,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
)
],
),
),
);
}
}
📌 Explanation:
- Each operation is controlled by a
bool
value usingCheckboxListTile
. - Multiple options can be selected together.
- Results for both are shown if both are checked.
📊 Summary Comparison
Feature | Radio Buttons | Checkboxes |
---|---|---|
Number of selections | Only one | One or more |
Widget used | RadioListTile |
CheckboxListTile |
Use case | Mutually exclusive operations | Combined or optional operations |
Result display | Single result | Multiple results (if selected) |
📚 Conclusion
Radio buttons and checkboxes are essential tools in Flutter when you need to capture user choices. This post demonstrated two real-world examples using a calculator to help you understand how and when to use each.
Try mixing both in your next Flutter form or quiz app to make it interactive and functional. Happy Fluttering! 🚀
0 Comments