Flutter Create Switch Widget with ON OFF Switch Event Android iOS Example Tutorial

Switch widget is just like a button that controls Toggle functionality. Switch is same as our house electricity switches which has Turn On and Turn Off functionality. Switch has a property named as onChanged which will called on Switch click event. If user turn on the Switch then this event called and also if user simply press on Switch this property calls. We can turn on and turn off Switch using onChanged event using State update. So in this tutorial we would Create Switch Widget with ON OFF Switch Event in Flutter Android iOS app example tutorial.

What we are doing in this tutorial:

We would Create a Switch widget in Flutter and update its value using onChanged method. We would also turn on and turn off switch using State and Update Text widget text.

Contents in this project Create Switch Widget with ON OFF Switch Event in Android iOS Example Tutorial:

1. Import material.dart package in your app’s main.dart file.

2. Create our main class named as MyApp extends with StatelessWidget. We would create Scaffold widget in Widget build area with SafeArea widget. We would call SwitchWidget() class function here to create switch widget. We would create SwitchWidget class in next step.

3. Create a class named as SwitchWidget extends StatefulWidget. This is our instance class for our Switch widget class. We would also call createState() function here which enables the State functionality in this class.

4. Create a class named as SwitchWidgetClass extends with State. We would create Switch widget here in this class.

5. Create 1 Boolean variable with 1 variable in SwitchWidgetClass.

  • switchControl : Used to turn ON and turn OFF switch using Boolean value.
  • textHolder : Hold some text which we would display in Text widget.

6. Create a function named as toggleSwitch() in SwitchWidgetClass. We would class this function on onChanged event of Switch widget.

7. Create Switch widget in widget build area in SwitchWidgetClass. We would put switch widget in Transform.scale() widget to make its size larger. We would also create a Text widget with textHolder value.

  • onChanged : Calls every time when user press or click on Switch.
  • value : Controls whether switch will be on or off using true – false bool value.
  • activeColor : Controls the Color of Switch round ball on Switch on.
  • activeTrackColor : Controls the Switch track bar color.
  • inactiveThumbColor : Controls Switch round ball color on Switch off event.
  • inactiveTrackColor : Controls the Switch track bar color on Switch off event.

8. Complete source code for main.dart file:

Screenshots in Android device:

Flutter Create Switch Widget with ON OFF Switch Event Android iOS Screenshot in iOS device:

Leave a Reply

Your email address will not be published.