FlutterGallery

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.

Basic Usage

  • 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];
});
},
)

Single selection

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;
});
},
)

Size

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")],
),

Colors

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)),
...
),

Button with icon

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)
],
),

API

For further information, please refer to the official documentation below.

Previous
Next