Toggle Button
The ToggleButton Widget is useful when you want the user to select one of several options.
Here we explain how to use the ToggleButton Widget provided by Flutter, as well as some examples of its application.
- ToggleButtons
ToggleButtons
is an effective way to create simple toggle buttons in Flutter.
final List<bool> selected = [true, false, false, false];ToggleButtons(isSelected: selected,children: const [Text("S"), Text("M"), Text("L"), Text("XL")],onPressed: (int index) {setState(() {selected[index] = !selected[index];});},)
By adjusting the value that goes into isSelected
, you can make a single selection.
int selectedIndex = 0;ToggleButtons(isSelected: selected,children: const [Text("S"), Text("M"), Text("L"), Text("XL")],onPressed: (int index) {setState(() {selectedIndex = index;});},)
By adjusting the value of constraints
, you can adjust the size of the button.
If you want to set the size to the full width, you can use MediaQuery
to do so.
ToggleButtons(isSelected: selected,constraints: BoxConstraints(minHeight: 40,minWidth: (MediaQuery.of(context).size.width - 36) / 4),onPressed: (int index) {setState(() {selected[index] = !selected[index];});},children: const [Text("S"), Text("M"), Text("L"), Text("XL")],),
You can adjust the color in detail, such as selectedBorderColor
(color of the currently selected border).
You can also change borderRadius
to adjust the roundness of the button.
ToggleButtons(color: Colors.red,fillColor: Colors.red[300],borderColor: Colors.red[100],splashColor: Colors.red[300],selectedBorderColor: Colors.red[800],selectedColor: Colors.white,borderRadius: const BorderRadius.all(Radius.circular(10)),...),
To improve UX, it is useful to display icons that make it easier to understand the meaning of buttons.Icon()
can be used to change the button text to an icon.
ToggleButtons(...children: const [Icon(Icons.sunny),Icon(Icons.nights_stay),Icon(Icons.brightness_4)],),
For further information, please refer to the official documentation below.