Switch
The Switch Widget is useful for getting a Boolean type (boolean true
or false
value) from the user.
Here we explain how to use the Switch Widget provided by Flutter, and give an example of its application.
- Switch
Switch
is useful if you want to create a general Switch button.
You can get whether the button is checked or not by onChanged
.
You can also set the value of onChanged
to Null to deactivate the button.
bool isChecked = true;Widget build(BuildContext context) {return Switch(value: isChecked,onChanged: (value) {setState(() {isChecked = value;});})}
- SwitchListTile
SwitchListTile
is useful when you want to create a Switch with a label.
You can change the value of the title
or subtitle
and add a description of the Switch.
Also, by using secondary
, a free widget such as an icon can be displayed next to the label.
SwitchListTile(title: const Text("Notification"),subtitle: const Text("Allow notifications"),secondary: const SizedBox(width: 40,height: 80,child: Icon(Icons.notifications_none_rounded),),value: isChecked,onChanged: (value) {setState(() {isChecked = value;});},),
activeTrackColor
: background color when value=trueinactiveTrackColor
: background color when value=false
The Switch Widget allows you to specify colors in detail by changing values such as
Switch(activeTrackColor: Colors.blue[800],inactiveTrackColor: Colors.blue[200],value: isChecked,onChanged: (value) {setState(() {isChecked = value;});}),
Using thumbIcon
, you can specify an icon within a button.
The icon can be changed depending on the button status, allowing for a high degree of freedom in setting the icon.
Switch(value: isChecked,onChanged: (value) {setState(() {isChecked = value;});},thumbIcon: MaterialStateProperty.resolveWith((states) {if (states.contains(MaterialState.selected)) {return const Icon(Icons.check);}return const Icon(Icons.close);}),)
For further information, please refer to the official documentation below.