How To Set Onchange Listener To Switch Using Flutter App

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

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.

How To Set Onchange Listener To Switch Using Flutter App

Onchange Listener To Switch
Complete Code For Onchange Listener To Switch In Flutter
main.dart

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());



class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyHomePageState();

}

class MyHomePageState extends State<MyHomePage> {
  bool _isChecked = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightGreen[700],
        title: Text("Swiutch Onchange Listener"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Center(
              child: Text(_isChecked ? "Switch On" : "Switch Off",
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.lightGreen[700],
                  )),
            ),
          ),
          Expanded(
              child: Container(
                height: 350.0,
                child: Column(
                  children: [
                    Switch(
                      activeColor: Colors.green,
                      value: _isChecked,
                      onChanged: (val) {
                        setState(() {
                          _isChecked = val;
                        });
                      },
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }
}

Related Post