Hello…
In this article I am gonna show you how to implement a switch widget in Flutter.
Watch Video Tutorial
The switch widget has the following syntax.
Switch(value: val, onChanged: (newVal) { print (newVal(); }) |
OnChange function is called when the user toggles the button.
We have to create a state variable in the parent Widget to hold the state of the switch widget and change the state variable when the user toggles the switch button.
Lets jump to the simple complete example…
Complete Example
import 'package:flutter/material.dart' ; class SwitchDemoScreen extends StatefulWidget { SwitchDemoScreen() : super (); final String title = "Switch App" ; @override _SwitchDemoScreenState createState() => _SwitchDemoScreenState(); } class _SwitchDemoScreenState extends State<SwitchDemoScreen> { bool val = false ; onSwitchValueChanged(bool newVal) { setState(() { val = newVal; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Flutter Switch Demo" , ), Switch( value: val, onChanged: (newVal) { onSwitchValueChanged(newVal); }) ], ), ), ); } } |
Source Code
You can download the complete source code from here.
Thanks for reading my article. Please leave your comments below.