Flutter Switch

 

Flutter Switch

A switch is a two-state user interface element used to toggle between ON (Checked) or OFF (Unchecked) states. Typically, it is a button with a thumb slider where the user can drag back and forth to choose an option in the form of ON or OFF. Its working is similar to the house electricity switches.

In Flutter, the switch is a widget used to select between two options, either ON or OFF. It does not maintain the state itself. To maintain the states, it will call the onChanged property. If the value return by this property is true, then the switch is ON and false when it is OFF. When this property is null, the switch widget is disabled. In this article, we are going to understand how to use a switch widget in the Flutter application.

Properties of Switch Widget

Some of the essential attributes of switch widget are given below:

AttributesDescriptions
onChangedIt will be called whenever the user taps on the switch.
valueIt contains a Boolean value true or false to control whether the switch functionality is ON or OFF.
activeColorIt is used to specify the color of the switch round ball when it is ON.
activeTrackColorIt specifies the switch track bar color.
inactiveThubmColorIt is used to specify the color of the switch round ball when it is OFF.
inactiveTrackColorIt specifies the switch track bar color when it is OFF.
dragStartBehaviorIt handled the drag start behavior. If we set it as DragStartBehavior.start, the drag moves the switch from on to off.

Example

In this application, we have defined a switch widget. Every time we toggled the switch widget, the onChanged property is called with a new state of the switch as value. To store the switch state, we have defined a boolean variable isSwitched that can be shown in the below code.

Open the IDE you are using, and create a Flutter application. Next, open the lib folder and replace main.dart with the following code.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() => runApp(MyApp());  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   @override  
  7.   Widget build(BuildContext context) {  
  8.     return MaterialApp(  
  9.         home: Scaffold(  
  10.             appBar: AppBar(  
  11.               backgroundColor: Colors.blue,  
  12.               title: Text("Flutter Switch Example"),  
  13.             ),  
  14.             body: Center(  
  15.                   child: SwitchScreen()  
  16.             ),  
  17.         )  
  18.     );  
  19.   }  
  20. }  
  21.   
  22. class SwitchScreen extends StatefulWidget {  
  23.   @override  
  24.   SwitchClass createState() => new SwitchClass();  
  25. }  
  26.   
  27. class SwitchClass extends State {  
  28.   bool isSwitched = false;  
  29.   var textValue = 'Switch is OFF';  
  30.   
  31.   void toggleSwitch(bool value) {  
  32.   
  33.     if(isSwitched == false)  
  34.     {  
  35.       setState(() {  
  36.         isSwitched = true;  
  37.         textValue = 'Switch Button is ON';  
  38.       });  
  39.       print('Switch Button is ON');  
  40.     }  
  41.     else  
  42.     {  
  43.       setState(() {  
  44.         isSwitched = false;  
  45.         textValue = 'Switch Button is OFF';  
  46.       });  
  47.       print('Switch Button is OFF');  
  48.     }  
  49.   }  
  50.   @override  
  51.   Widget build(BuildContext context) {  
  52.     return Column(  
  53.         mainAxisAlignment: MainAxisAlignment.center,  
  54.         children:[ Transform.scale(  
  55.             scale: 2,  
  56.             child: Switch(  
  57.               onChanged: toggleSwitch,  
  58.               value: isSwitched,  
  59.               activeColor: Colors.blue,  
  60.               activeTrackColor: Colors.yellow,  
  61.               inactiveThumbColor: Colors.redAccent,  
  62.               inactiveTrackColor: Colors.orange,  
  63.             )  
  64.           ),  
  65.           Text('$textValue', style: TextStyle(fontSize: 20),)  
  66.         ]);  
  67.   }  
  68. }  

Output:

When we run the application in the emulator or device, we should get UI similar to the following screenshot

Flutter Switch

If we press on the switch, it will change their state from OFF to ON. See the below screenshot:

Flutter Switch

How to customize the Switch button in Flutter?

Flutter also allows the user to customize their switch button. Customization makes the user interface more interactive. We can do this by adding the custom-switch dependency in the pubspec.yaml file and then import it into the dart file.

Example:

Open the main.dart file and replace it with the following code:

  1. import 'package:flutter/material.dart';  
  2. import 'package:custom_switch/custom_switch.dart';  
  3.   
  4. void main() => runApp(MyApp());  
  5.   
  6. class MyApp extends StatelessWidget {  
  7.   @override  
  8.   Widget build(BuildContext context) {  
  9.     return MaterialApp(  
  10.         home: Scaffold(  
  11.             appBar: AppBar(  
  12.               backgroundColor: Colors.blue,  
  13.               title: Text("Custom Switch Example"),  
  14.             ),  
  15.             body: Center(  
  16.                   child: SwitchScreen()  
  17.             ),  
  18.         )  
  19.     );  
  20.   }  
  21. }  
  22.   
  23. class SwitchScreen extends StatefulWidget {  
  24.   @override  
  25.   SwitchClass createState() => new SwitchClass();  
  26. }  
  27.   
  28. class SwitchClass extends State {  
  29.   bool isSwitched = false;  
  30.   @override  
  31.   Widget build(BuildContext context) {  
  32.     return Column(  
  33.         mainAxisAlignment: MainAxisAlignment.center,  
  34.         children:<Widget>[  
  35.             CustomSwitch(  
  36.               value: isSwitched,  
  37.               activeColor: Colors.blue,  
  38.               onChanged: (value) {  
  39.                 print("VALUE : $value");  
  40.                 setState(() {  
  41.                   isSwitched = value;  
  42.                 });  
  43.               },  
  44.             ),  
  45.           SizedBox(height: 15.0,),  
  46.           Text('Value : $isSwitched', style: TextStyle(color: Colors.red,  
  47.               fontSize: 25.0),)  
  48.         ]);  
  49.     }  
  50. }  

Output:

When we run the application in the emulator or device, we should get UI similar to the following screenshot:

Flutter Switch

If we press on the switch, it will change their state from OFF to ON. See the below screenshot:

Flutter Switch


Post a Comment

Previous Post Next Post