DEV Community

Cover image for A Short Tutorial on How to Develop a Switch button in Flutter.
Maadhav
Maadhav

Posted on

4

A Short Tutorial on How to Develop a Switch button in Flutter.

A Short Tutorial on How to Develop a Switch button in Flutter.

Flutter Switch is used to toggle a setting between on/off which is true/false respectively.

When the switch is on, the value returned by the Switch onChanged property is true, while the switch is off, onChanged property returns false.

In the following example Flutter application, we defined a Switch widget. Whenever the Switch is toggled, onChanged is called with new state of Switch as value.

We have defined a boolean variable isSwitched to store the state of Switch.

Create a basic Flutter application and replace main.dart with the following code.

main.dart

Complete Source Code…

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isSwitched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text("Flutter Switch Example"),
),
body: Center(
child: Switch(
value: isSwitched,
onChanged: (value){
setState(() {
isSwitched=value;
print(isSwitched);
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
),
);
}
}
view raw main.dart hosted with ❤ by GitHub

I have started this new series named Flutter Shorts in which I will share some simple and useful tutorials related to Flutter Widgets.

So Stay Tuned for more…

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more