How to Add Switches In Flutter

List of phone settings. Each setting has a switch which is critical to learn how to add switches in flutter
Credit to: Google | Material Design

Switches toggle the state of a single item on or off. This specific widget is one of the most used widgets in flutter as a number of apps in the Play Store and App Store are increasingly utilizing this widget as it immediately activates or deactivates something. Besides that, switches can be on or off. They can also be enabled, hovered over, focused, or pressed. That is why it is important for us as developers to learn how to add switches in Flutter.

Fundamentals of Switches In Flutter

Before we start implementing switches in Flutter, you must first understand that switches have been in user interfaces for a long time and should be used as expected. Secondly, the reason why it’s efficient is because switches make it easy to compare available options. Aside from that, switches should be visible at a glance if a switch has been selected, and selected items should be more visually prominent than unselected items. This makes it scannable for the users.

One might wonder why switches are used when radio buttons are already available. The answer to that is that if each item in a set can be controlled independently, switches should be used instead of radio buttons. On the other hand, use radio buttons to turn stuff on or off. Radio buttons indicate that a group of things are alternatives and that only one can be chosen at a time. Use switches instead.

Implementation codes

Column(
children: [
for (int i = 0; i <= count; i++)
ListTile(
title: Text(
‘Switch ${i + 1}’,
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: i == count ? Colors.black38 : Colors.black),
),
leading: Switch(
value: _values[i],
activeColor: Color(0xFF6200EE),
onChanged: i == count
? null
: (bool value) {
setState(() {
_values[i] = value;
});
},
),
),
],
)

Conclusion

To conclude, switches are one of the most used widgets in flutter as they immediately activate or deactivate something. Besides that, switches can be enabled, hovered over, focused on, or pressed. One might wonder why switches are used when radio buttons are already available. The answer is that if each item in a set can be controlled independently, switches should be used instead of radio buttons. Additionally, if you find this blog outdated, you can always check the official documentation here. Moreover, If you found it useful, please share it with your friends and family. You can subscribe to my latest blogs here. Thank you for reading!

Leave a Comment

Your email address will not be published. Required fields are marked *