Flutter Switch Widget: A Guide to Implementing and Customizing Switches

The Flutter Switch widget is a simple yet powerful widget that allows users to toggle between two states. This blog post will provide a comprehensive guide on how to implement the Switch widget in your Flutter app and customize it to fit your design. 

We will cover the basics of the Switch widget, including its properties and events, and demonstrate how to create and customize switches using code samples.

Flutter Switch Widget Code:


import 'package:flutter/material.dart';

class BasicWidgetSwitch extends StatefulWidget {
  const BasicWidgetSwitch({Key? key}) : super(key: key);

  @override
  State createState() => _BasicWidgetSwitchState();
}

class _BasicWidgetSwitchState extends State<BasicWidgetSwitch> {
  bool switchValue = false;
  bool switchValueA = false;
  bool switchValueB = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
      child: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max, // set mainAxisSize to max
            children: [
              //........................................ switch
              // Switches
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Switch(
                    value: switchValueA,
                    onChanged: (value) {
                      setState(() {
                        switchValueA = value;
                      });
                    },
                  ),
                  Switch(
                    value: switchValueB,
                    onChanged: (value) {
                      setState(() {
                        switchValueB = value;
                      });
                    },
                  ),
                ],
              ),

              // Disabled switches
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Switch(
                    value: switchValueA,
                    onChanged: null,
                  ),
                  Switch(
                    value: switchValueB,
                    onChanged: null,
                  ),
                ],
              ),
            ]),
      ),
    ));
  }
}

..

Flutter Widget Tutorial: Building an Adaptive Switch

This tutorial will show you how to build an adaptive switch widget in Flutter that automatically adjusts its appearance based on the user's device platform. This ensures a consistent user experience across different platforms, such as Android and iOS.


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class BasicWidgetSwitch extends StatefulWidget {
  const BasicWidgetSwitch({Key? key}) : super(key: key);

  @override
  State createState() => _BasicWidgetSwitchState();
}

class _BasicWidgetSwitchState extends State<BasicWidgetSwitch> {

  // initialize switch values
  bool _value = false;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        body: SingleChildScrollView(
          child: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.max, // set mainAxisSize to max
                children: [

                  // Adaptive Switch
                  AdaptiveSwitch(
                      value: _value,
                      onChanged: (bool newValue) {
                        setState(() {
                          _value = newValue;
                        });
                      }),

                ]),
          ),
        ));
  }
}

// Widget to adapt to platform-specific switch design
class AdaptiveSwitch extends StatefulWidget {
  final bool value;
  final ValueChanged onChanged;

  // constructor to initialize switch value and onChanged callback
  const AdaptiveSwitch({super.key, required this.value, required this.onChanged});

  @override
  AdaptiveSwitchStateState createState() => AdaptiveSwitchStateState();
}

class AdaptiveSwitchStateState extends State {
  bool _value = false;

  @override
  void initState() {
    super.initState();
    _value = widget.value; // set initial switch value
  }

  @override
  Widget build(BuildContext context) {
    // check platform to use appropriate switch widget
    return Theme.of(context).platform == TargetPlatform.iOS
        ? CupertinoSwitch(
      value: _value, // use state value
      onChanged: (bool newValue) {
        setState(() {
          _value = newValue; // update state value
        });
        widget.onChanged(newValue); // call parent onChanged callback
      },
    )
        : Switch(
      value: _value, // use state value
      onChanged: (bool newValue) {
        setState(() {
          _value = newValue; // update state value
        });
        widget.onChanged(newValue); // call parent onChanged callback
      },
    );
  }
}

..

Flutter Widget Examples - Thumb Image Switch

This code is an example of using the Thumb Image Switch widget in Flutter, which is a switch widget that allows you to use images for the thumb icon. 

This code demonstrates how to create and use the Thumb Image Switch widget in a Flutter app.


import 'package:flutter/material.dart';

class BasicWidgetSwitch extends StatefulWidget {
  const BasicWidgetSwitch({Key? key}) : super(key: key);

  @override
  State createState() => _BasicWidgetSwitchState();
}

class _BasicWidgetSwitchState extends State<BasicWidgetSwitch> {
  bool switchValue = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
      child: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max, // set mainAxisSize to max
            children: [
              // Thumb Image Switch
              ThumbImageSwitch(onChanged: (value) {
                setState(() {
                  switchValue = value;
                });
              }),
            ]),
      ),
    ));
  }
}

class ThumbImageSwitch extends StatefulWidget {
  final ValueChanged? onChanged;

  const ThumbImageSwitch({Key? key, this.onChanged}) : super(key: key);

  @override
  State createState() => _ThumbImageSwitchState();
}

class _ThumbImageSwitchState extends State {
  bool isSwitched = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          // Switch with thumb images
          Padding(
            padding: const EdgeInsets.all(50.0),
            child: Switch(
              activeThumbImage:
                  Image.asset('assets/images/thumbs_up.png').image,
              activeColor: Colors.black,
              inactiveThumbImage:
                  Image.asset('assets/images/thumbs_down.png').image,
              inactiveTrackColor: Colors.amberAccent.shade100,
              value: isSwitched,
              onChanged: (value) {
                setState(() {
                  isSwitched = value;
                });
                // Trigger onChanged event with new value
                if (widget.onChanged != null) {
                  widget.onChanged!(value);
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}

..

You need to add the asset 'assets/images/' to this directory




Comments