Checkbox in Flutter
Introduction
Checkbox is a widget that allows users to select between two states: checked or unchecked. This is typically used in forms and settings to enable or disable options.
Example 1: Basic Checkbox
In this example, you will learn to create a simple checkbox using the Checkbox widget.
Checkbox(
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
),
Example 2: Checkbox with Custom Colors
In this example, you will learn to create a checkbox with custom colors using the Checkbox widget.
Checkbox(
value: isChecked,
checkColor: Colors.white, // color of tick Mark
activeColor: Colors.green, // background color
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
)
Example 3: Checkbox List
In this example, you will learn to create a group of checkboxes using the CheckboxListTile widget.
var options = <String>['Option 1', 'Option 2', 'Option 3', 'Option 4'];
var selectedOptions = <String>[];
ListView(
children: options.map((String option) {
return CheckboxListTile(
title: Text(option),
value: selectedOptions.contains(option),
onChanged: (bool? value) {
setState(() {
if (value == true) {
selectedOptions.add(option);
} else {
selectedOptions.remove(option);
}
});
},
);
}).toList(),
)
Example 4: Accept Terms & Conditions Checkbox
In this example, you will learn to create a checkbox for accepting terms and conditions using the CheckboxListTile widget.
Form(
child: Column(
children: [
CheckboxListTile(
title: Text("Accept Terms & Conditions"),
value: isAccepted,
onChanged: (bool? value) {
setState(() {
isAccepted = value!;
});
},
),
// Other form elements
],
),
)
Example 5: Interest Selection Checkbox
In this example, you will learn to find the selected interests from a list of interests using the CheckboxListTile widget.
List<String> interests = [
'Reading',
'Music',
'Travel',
'Sports',
'Cooking',
];
List<String> selectedInterests = [];
Column(
children: interests.map((String interest) {
return CheckboxListTile(
title: Text(interest),
value: selectedInterests.contains(interest),
onChanged: (bool? value) {
setState(() {
if (value == true) {
selectedInterests.add(interest);
} else {
selectedInterests.remove(interest);
}
});
},
);
}).toList(),
)
Challenge
Create a checkbox group for selecting multiple programming languages from a list of languages.
// available programming languages
List<String> languages = [
'Dart',
'Python',
'Java',
'JavaScript',
'C++',
'C#',
'Ruby',
'Go',
'Swift',
'Kotlin',
];