Flutter Switch

A switch is a two-state user interface element that can be toggled between ON (Checked) and OFF (Unchecked). It is usually a button with a thumb slider that the user can drag back and forth to select an ON or OFF option. Its operation is comparable to that of a home’s electrical switches.

The switch is a widget in Flutter that allows you to choose between two options: ON or OFF. It is not responsible for the state’s upkeep. It will use the onChanged property to keep track of the states. The switch is ON if the value returned by this property is true, and it is off if the value returned by this property is false. The switch widget is disabled when this property is null. We’re going to learn how to use a switch widget in a Flutter application in this tutorial.


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.

import 'package:flutter/material.dart';

void main() {
    home: MyApp(),

class MyApp extends StatefulWidget {
  _State createState() => _State();

class _State extends State<MyApp> {
  bool isSwitched = false;

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Learn Code Zone'),
        body: Center(
          child: Switch(
            value: isSwitched,
            onChanged: (value) {
              setState(() {
                isSwitched = value;
            activeTrackColor: Colors.lightGreenAccent,
            activeColor: Colors.green,


Leave a Reply

Your email address will not be published. Required fields are marked *