Education
Software Development Executive - I
Software Development Executive - II
Last updated on Jan 10, 2024
Last updated on Dec 25, 2023
Toggle buttons are crucial in designing a user interface, especially for Flutter apps. They offer a visual representation of a binary choice, such as on/off or yes/no scenarios, an essential function in many applications.
A toggle button in Flutter is a widget that can switch between two states. It is commonly represented as a switch, checkbox, or a custom button that allows the user to toggle between an active (selected) state and an inactive (deselected) state.
Toggle buttons are used in various user interface parts to control settings, change preferences, or as part of a form input. They are designed to provide immediate feedback, making it clear to users that their selection has been registered.
A simple toggle switch widget is a user interface element that allows users to switch between two states, typically on and off. In Flutter, this is represented by the Switch widget.
Here's a basic example of how to create a simple toggle switch widget:
1import 'package:flutter/material.dart'; 2 3void main() => runApp(MyApp()); 4 5class MyApp extends StatelessWidget { 6 7 Widget build(BuildContext context) { 8 return MaterialApp( 9 home: Scaffold( 10 appBar: AppBar( 11 title: Text('Simple Toggle Switch'), 12 ), 13 body: Center( 14 child: ToggleSwitch(), 15 ), 16 ), 17 ); 18 } 19} 20 21class ToggleSwitch extends StatefulWidget { 22 23 _ToggleSwitchState createState() => _ToggleSwitchState(); 24} 25 26class _ToggleSwitchState extends State<ToggleSwitch> { 27 bool isSwitched = false; 28 29 void _toggleSwitch(bool value) { 30 setState(() { 31 isSwitched = value; 32 }); 33 } 34 35 36 Widget build(BuildContext context) { 37 return Switch( 38 value: isSwitched, 39 onChanged: _toggleSwitch, 40 activeTrackColor: Colors.lightGreenAccent, 41 activeColor: Colors.green, 42 ); 43 } 44} 45
In this code snippet, we have a MyApp class that creates the main application widget. Inside, we have a ToggleSwitch stateful widget that manages the state of the switch. The _ToggleSwitchState class contains the logic to handle the state change when the switch is toggled.
Customization can be applied to various aspects of a toggle button, including:
To customize the dimensions and shape of your toggle button, you can wrap it in other widgets that allow size and border-radius adjustments. Here's an example:
1Switch( 2 value: isSwitched, 3 onChanged: _toggleSwitch, 4 activeTrackColor: Colors.lightGreenAccent, 5 activeColor: Colors.green, 6 materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, // Reduces the tap target size 7 // Wrap the Switch in a Transform.scale to adjust the size 8 switchSize: Transform.scale( 9 scale: 1.5, // Increase the size by 50% 10 child: Switch( 11 value: isSwitched, 12 onChanged: _toggleSwitch, 13 ), 14 ), 15) 16
An animated toggle switch provides a visual transition between states, making the user interface more dynamic and engaging. Animation can help indicate the action taken by the user, reinforcing the app's interactivity.
Flutter's AnimatedSwitcher widget can be used to animate the transition between two child widgets automatically. Here's how you can use it to animate a toggle switch:
1class AnimatedToggleSwitch extends StatefulWidget { 2 3 _AnimatedToggleSwitchState createState() => _AnimatedToggleSwitchState(); 4} 5 6class _AnimatedToggleSwitchState extends State<AnimatedToggleSwitch> { 7 bool isSwitched = false; 8 9 10 Widget build(BuildContext context) { 11 return GestureDetector( 12 onTap: () { 13 setState(() { 14 isSwitched = !isSwitched; 15 }); 16 }, 17 child: AnimatedContainer( 18 duration: Duration(milliseconds: 300), 19 height: 40.0, 20 width: 100.0, 21 decoration: BoxDecoration( 22 borderRadius: BorderRadius.circular(20.0), 23 color: isSwitched ? Colors.green : Colors.redAccent, 24 ), 25 child: Stack( 26 children: <Widget>[ 27 AnimatedPositioned( 28 duration: Duration(milliseconds: 300), 29 curve: Curves.easeIn, 30 top: 3.0, 31 left: isSwitched ? 60.0 : 0.0, 32 right: isSwitched ? 0.0 : 60.0, 33 child: AnimatedSwitcher( 34 duration: Duration(milliseconds: 300), 35 transitionBuilder: (Widget child, Animation<double> animation) { 36 return RotationTransition( 37 turns: animation, 38 child: child, 39 ); 40 }, 41 child: isSwitched 42 ? Icon( 43 Icons.check_circle, 44 color: Colors.white, 45 key: UniqueKey(), 46 ) 47 : Icon( 48 Icons.remove_circle_outline, 49 color: Colors.white, 50 key: UniqueKey(), 51 ), 52 ), 53 ), 54 ], 55 ), 56 ), 57 ); 58 } 59} 60
In this example, the AnimatedSwitcher animates between two icons representing the on and off states of the switch. The ScaleTransition builder provides a scaling effect to the transition.
You can group toggle buttons when you need to present users with multiple options. Here's an example of how to implement a row of multiple toggle buttons, each representing a different option:
1class MultipleToggleButtons extends StatefulWidget { 2 3 _MultipleToggleButtonsState createState() => _MultipleToggleButtonsState(); 4} 5 6class _MultipleToggleButtonsState extends State<MultipleToggleButtons> { 7 List<bool> isSelected = [false, false, false]; 8 9 10 Widget build(BuildContext context) { 11 return ToggleButtons( 12 children: <Widget>[ 13 Icon(Icons.ac_unit), 14 Icon(Icons.call), 15 Icon(Icons.cake), 16 ], 17 onPressed: (int index) { 18 setState(() { 19 isSelected[index] = !isSelected[index]; 20 }); 21 }, 22 isSelected: isSelected, 23 ); 24 } 25} 26
In this code snippet, ToggleButtons is a widget that creates a set of toggle buttons. The isSelected list contains boolean values corresponding to each button's selection state.
A stateful widget is essential for toggle buttons because it allows the widget to maintain state changes over time. When a user interacts with a toggle button, the widget's state needs to be updated to reflect the new value, which updates the user interface.
The state can be a simple boolean value for binary choices, such as an on/off switch. However, when dealing with multiple options or buttons, the state might be a list of boolean values or a more complex data structure.
Here's an example of using a StatefulWidget to manage the state of a toggle button:
1class CustomToggleButton extends StatefulWidget { 2 3 _CustomToggleButtonState createState() => _CustomToggleButtonState(); 4} 5 6class _CustomToggleButtonState extends State<CustomToggleButton> { 7 bool isToggled = false; 8 9 10 Widget build(BuildContext context) { 11 return GestureDetector( 12 onTap: () { 13 setState(() { 14 isToggled = !isToggled; 15 }); 16 }, 17 child: Container( 18 width: 100, 19 height: 50, 20 decoration: BoxDecoration( 21 color: isToggled ? Colors.green : Colors.grey, 22 borderRadius: BorderRadius.circular(25), 23 ), 24 child: Center( 25 child: Text( 26 isToggled ? 'ON' : 'OFF', 27 style: TextStyle(color: Colors.white), 28 ), 29 ), 30 ), 31 ); 32 } 33} 34
In this code snippet, the CustomToggleButton stateful widget toggles its state between true and false when the user taps on it, and the UI is updated accordingly to reflect the change.
Creating toggle buttons that are accessible and responsive is essential to accommodate all users and devices. This ensures that your Flutter app provides an inclusive experience, regardless of the user's needs or device.
Accessibility features help users with disabilities interact with your app. For toggle buttons, this means:
Here's an example of adding accessibility features to a toggle button:
1Switch( 2 value: isSwitched, 3 onChanged: _toggleSwitch, 4 activeTrackColor: Colors.lightGreenAccent, 5 activeColor: Colors.green, 6 materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, 7 semanticsLabel: isSwitched ? 'Disable Settings' : 'Enable Settings', 8) 9
Responsiveness ensures that toggle buttons look and function correctly on different screen sizes and orientations. To achieve this:
Here's a basic example of using media queries for responsive toggle buttons:
1Widget build(BuildContext context) { 2 var screenSize = MediaQuery.of(context).size; 3 4 return Switch( 5 value: isSwitched, 6 onChanged: _toggleSwitch, 7 activeTrackColor: Colors.lightGreenAccent, 8 activeColor: Colors.green, 9 materialTapTargetSize: screenSize.width > 600 10 ? MaterialTapTargetSize.padded 11 : MaterialTapTargetSize.shrinkWrap, 12 ); 13} 14
Toggle buttons are a versatile and essential component in the design of user interfaces for Flutter apps. Throughout this post, we've explored the various aspects of creating and customizing toggle buttons, from simple switches to fully animated and responsive options.
By understanding the principles behind toggle buttons and implementing them thoughtfully, you can greatly improve the interactivity and functionality of your mobile applications.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.
Tired coding all day?
Do it with a few clicks.