Open In App

Flutter – Custom Gradient Switch

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

If you are using Flutter you must hear that it is very easy to make UI in this. All widgets are easy to use. So now let’s make one common widget that you must have seen in almost every app i.e. Switch. Now you will say it is very easy to make from the switch widget. But we will make it a Gradient Switch. If you are new to Flutter let us explain what Switch is. It is used to toggle the on/off state of a single setting. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Add one variable to check the switch current status

Dart




bool isSwitchOn = false;


Step 3: Create a Gesture Detector with Stack as a widget

We have used gestureDetecture to detect user clicks and stack because will stack two containers to make it look like a switch.

Dart




GestureDetector(
               onTap: () {               
               },
                
               child: Stack(
                 alignment:
                     isSwitchOn ? Alignment.centerRight : Alignment.centerLeft,
                 children: [
                 
                 ],
               ),
             ),


In stack we have passed alignment on ternary operator because we need to show the container in two different alignment on the basis of isSwitch value.

Step 4: Add 2 Container in Stack

First Container with following property

Properties:

  • height, width: We have added fixed height width so that it remains same in responsiveness also
  • alignment: We haved Alignment.center as all the child will be requiring incenter only
  • decoration: In Box Decoration there multiple properties you can use and modify this switch but we have used only 2 properties. 1 most important gradient in this we will be passing the linear gradient with 2 different colors on condition and borderradius for making switch beautiful.

Dart




Container(
           // Fixed height and width is given so that 
              // it won't get change in responsiveness
           width: 70,
           height: 40,
           alignment: Alignment.center, // Alignment as center
                     decoration: BoxDecoration(
                       // TODO: you can change here gradient color
                       gradient: LinearGradient(
                         colors: isChecked
                             ? [
                                 const Color(0xFFF09869),
                                 const Color(0xFFC729B2),
                               ]
                             : [Colors.grey, Colors.grey],
                       ),
                       borderRadius:
                           const BorderRadius.all(Radius.circular(40)),
                     ),
                   ),


Second Container with following property

Properties:

  • height, width: We have added fixed height width so that it remains same in responsiveness also
  • alignment: We haved Alignment.center as all the child will be requiring incenter only
  • decoration: In Box Decoration there multiple properties you can use and modify this switch but we have used only 2 properties. 1 most important gradient in this we will be passing the linear gradient with 2 different colors on condition and borderradius for making switch beautiful.

Dart




Container(
          height: 40,
          width: 40,
          decoration: const BoxDecoration(
                         shape: BoxShape.circle, color: Colors.white),
          ),


Step 4: Change the state of bool variable

In GestureDetector we have added onTap where we will be changing the state of isSwitchOn variable

Dart




onTap: () {
           // To change the state of isSwitchOn variable
           setState(() {
                    isSwitchOn = !isSwitchOn;
               });
           },


We have completed all the steps let’s understand

What we have done?

We have Gesture detector which will onTap function use to change the state of switch in child we have stack with alignment on conditional basis of isSwitchOn if it is true it will be right aligned otherwise it will be left. Inside Stack we have children with two container first one is gradient container and small whitecontainer on it.

Complete Source Code

Dart




import 'package:flutter/material.dart';
  
// You can also use stateful builder instead of stateful widget
class GradientSwitch extends StatefulWidget {
  const GradientSwitch({Key? key}) : super(key: key);
  
  @override
  State<GradientSwitch> createState() => _GradientSwitchState();
}
  
class _GradientSwitchState extends State<GradientSwitch> {
  bool isSwitchOn = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          title: const Text('Gradient Switch'),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  // To change the state of isSwitchOn variable
                  setState(() {
                    isSwitchOn = !isSwitchOn;
                  });
                },
                // TODO: Here you can see border of Switch if isSwitchOn is true
                // else gradient color of Switch
                child: Stack(
                  alignment:
                      isSwitchOn ? Alignment.centerRight : Alignment.centerLeft,
                  children: [
                    // Gradient Container
                    Container(
                      // Fixed height and width is given so that
                      // it won't get change in responsiveness
                      width: 70,
                      height: 40,
                      alignment: Alignment.center, // Alignment as center
                      decoration: BoxDecoration(
                        // TODO: you can change here gradient color
                        gradient: LinearGradient(
                          colors: isSwitchOn
                              ? [
                                  const Color(0xFFF09869),
                                  const Color(0xFFC729B2),
                                ]
                              : [Colors.grey, Colors.grey],
                        ),
                        borderRadius:
                            const BorderRadius.all(Radius.circular(40)),
                      ),
                    ),
                    // White Ball like Container
                    Container(
                      height: 40,
                      width: 40,
                      decoration: const BoxDecoration(
                          shape: BoxShape.circle, color: Colors.white),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              Text(
                'Custom Gradient Switch',
                style: Theme.of(context).textTheme.displaySmall,
              ),
            ],
          ),
        ));
  }
}


How it will work?

Whenever user click on custom switch it will change it state if is enable it will show gradient type widget with white ball like container in right. Otherwise it will be grey color with ball at left corner.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads