A simple toggle switch widget for Flutter.

Overview

Toggle Switch

A simple toggle switch widget. It can be fully customized with desired icons, width, colors, text, corner radius, animation etc. It also maintains selection state.

Getting Started

In the pubspec.yaml of your flutter project, add the following dependency:

dependencies:
  ...
  toggle_switch: ^1.3.0

Import it:

import 'package:toggle_switch/toggle_switch.dart';

Usage Examples

Basic toggle switch

// Here, default theme colors are used for activeBgColor, activeFgColor, inactiveBgColor and inactiveFgColor
ToggleSwitch(
  initialLabelIndex: 0,
  totalSwitches: 3,
  labels: ['America', 'Canada', 'Mexico'],
  onToggle: (index) {
    print('switched to: $index');
  },
),

Basic toggle switch

Basic toggle switch with custom height and font size

ToggleSwitch(
  minWidth: 90.0,
  minHeight: 90.0,
  fontSize: 16.0,
  initialLabelIndex: 1,
  activeBgColor: [Colors.green],
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.grey[900],
  totalSwitches: 3,
  labels: ['Tall', 'Grande', 'Venti'],
  onToggle: (index) {
    print('switched to: $index');
  },
),

Basic toggle switch with custom height and font size

With text or icon

ToggleSwitch(
  minWidth: 90.0,
  cornerRadius: 20.0,
  activeBgColors: [[Colors.cyan], [Colors.redAccent]],
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  totalSwitches: 2,
  labels: ['YES', ''],
  icons: [null, FontAwesomeIcons.times],
  onToggle: (index) {
    print('switched to: $index');
  },
),

With text or icon

With icons, text and different active background colors

ToggleSwitch(
  minWidth: 90.0,
  initialLabelIndex: 1,
  cornerRadius: 20.0,
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  totalSwitches: 2,
  labels: ['Male', 'Female'],
  icons: [FontAwesomeIcons.mars, FontAwesomeIcons.venus],
  activeBgColors: [[Colors.blue],[Colors.pink]],
  onToggle: (index) {
    print('switched to: $index');
  },
),

With icons, text and different active background colors

With border color, border width, icons, custom height and different active background colors

ToggleSwitch(
  minWidth: 90.0,
  minHeight: 70.0,
  initialLabelIndex: 2,
  cornerRadius: 20.0,
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  totalSwitches: 3,
  icons: [
    FontAwesomeIcons.mars,
    FontAwesomeIcons.venus,
    FontAwesomeIcons.transgender
  ],
  iconSize: 30.0,
  borderWidth: 2.0,
  borderColor: [Colors.blueGrey],
  activeBgColors: [[Colors.blue], [Colors.pink], [Colors.purple]],
  onToggle: (index) {
    print('switched to: $index');
  },
),

With border color, border width, icons, custom height and different active background colors

With gradient border color, divider color and gradient active background colors

ToggleSwitch(
  minWidth: 90.0,
  minHeight: 70.0,
  initialLabelIndex: 0,
  cornerRadius: 20.0,
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  totalSwitches: 3,
  icons: [
    FontAwesomeIcons.facebook,
    FontAwesomeIcons.twitter,
    FontAwesomeIcons.instagram
  ],
  iconSize: 30.0,
  borderColor: [Color(0xff3b5998), Color(0xff8b9dc3), Color(0xff00aeff), Color(0xff0077f2), Color(0xff962fbf), Color(0xff4f5bd5)],
  dividerColor: Colors.blueGrey,
  activeBgColors: [[Color(0xff3b5998), Color(0xff8b9dc3)], [Color(0xff00aeff), Color(0xff0077f2)], [Color(0xfffeda75), Color(0xfffa7e1e), Color(0xffd62976), Color(0xff962fbf), Color(0xff4f5bd5)]],
  onToggle: (index) {
    print('switched to: $index');
  },
),

With gradient border color, divider color and gradient active background colors

With bounceInOut animation

ToggleSwitch(
  minWidth: 90.0,
  minHeight: 70.0,
  initialLabelIndex: 0,
  cornerRadius: 20.0,
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  totalSwitches: 2,
  icons: [
    FontAwesomeIcons.lightbulb,
    FontAwesomeIcons.solidLightbulb,
  ],
  iconSize: 30.0,
  activeBgColors: [[Colors.black45, Colors.black26], [Colors.yellow, Colors.orange]],
  animate: true, // with just animate set to true, default curve = Curves.easeIn
  curve: Curves.bounceInOut, // animate must be set to true when using custom curve
  onToggle: (index) {
    print('switched to: $index');
  },
),

With bounceInOut animation

With radius style

ToggleSwitch(
  minWidth: 90.0,
  cornerRadius: 20.0,
  activeBgColors: [[Colors.green[800]!], [Colors.red[800]!]],
  activeFgColor: Colors.white,
  inactiveBgColor: Colors.grey,
  inactiveFgColor: Colors.white,
  initialLabelIndex: 1,
  totalSwitches: 2,
  labels: ['True', 'False'],
  radiusStyle: true,
  onToggle: (index) {
    print('switched to: $index');
  },
),

With radius style

With custom text styles

ToggleSwitch(
  minWidth: 90.0,
  cornerRadius: 20.0,
  inactiveFgColor: Colors.white,
  initialLabelIndex: 1,
  totalSwitches: 3,
  labels: ['Normal', 'Bold', 'Italic'],
  customTextStyles: [
    null,
    TextStyle(
        color: Colors.brown,
        fontSize: 18.0,
        fontWeight: FontWeight.w900),
    TextStyle(
        color: Colors.black,
        fontSize: 16.0,
        fontStyle: FontStyle.italic)
  ],
  onToggle: (index) {
    print('switched to: $index');
  },
),

With custom text styles

With custom icons

ToggleSwitch(
    minWidth: 90.0,
    minHeight: 90.0,
    cornerRadius: 20.0,
    activeBgColors: [
        [Color(0xfffdbb0a)],
        [Colors.black54],
        [Colors.white54]
    ],
    inactiveFgColor: Colors.white,
    initialLabelIndex: 2,
    totalSwitches: 3,
    customIcons: [
        Icon(
            FontAwesomeIcons.ccVisa,
            color: Color(0xff1a1f71),
            size: 55.0,
        ),
        Icon(
            FontAwesomeIcons.ccMastercard,
            color: Color(0xffF79E1B),
            size: 55.0,
        ),
        Icon(
            FontAwesomeIcons.ccAmex,
            color: Color(0xff27AEE3),
            size: 55.0,
        )
    ],
    onToggle: (index) {
        print('switched to: $index');
    },
),

With custom icons

setState() inside onToggle

Example code with explanation

Credits

Eugene

Comments
  • (radiusStyle: false) does not work when textDirection is set to TextDirection.rtl

    (radiusStyle: false) does not work when textDirection is set to TextDirection.rtl

    Hello, I upgraded to the new version, in the new version all the buttons are rounded at the borders. radiusStyle: false has no effect !!

    I mean the connection border between the two buttons. Not like before. d8d18130-d5a2-42b9-af18-a2b552f7bd35

    bug fixed 
    opened by ali-1989 10
  • How to change value programmatically

    How to change value programmatically

    How do I update the toggleswitch programmatically?

    I have tried using ValueListenableBuilder and changing initialLabelIndex but I wonder if there could be a better way, also this seems that isn't always working

    opened by robertsLando 9
  • SetState Switch wrong values on mistouch.

    SetState Switch wrong values on mistouch.

    Hi, I found this package to be very amazing but there is a strange issue that I just noticed. I saw that setState wasn't working at first in the switch. Luckily I found the example on this page. But there's is something I just noticed.

    Let's say we have two values [User, Service Provider]

    Now I have radiovalue variable set to 0.

      onToggle: (val){
                            print(radioval);
                            setState(() {
                              radioval = val;
                            });
    
                          },
    

    The issue is that if a person in mistake presses the selected box more than once the value changes.

    for an instance before touch the value for user was 0 and service provider was 1 and if user selected the user button more than once the value will change from 0 to 1 and service provider's value will become 0 and vice versa.

    This is the issue. Is it possible to not change the value for selected index?

    opened by Umar-Khan-Yousafzai 8
  • setState in onToggle doesn't switch without showing an error

    setState in onToggle doesn't switch without showing an error

    When doing a setState() in the onToggle() function, suddenly it doesn't switch to the other value anymore but no error is occurring. Even the state value is switching properly but the view doesn't get updated.

    Everything works fine until I try to add some state, what am I doing wrong?

    Best regards.

    question 
    opened by jogee 6
  • setState  function doesnot work with the toggle

    setState function doesnot work with the toggle

    Describe the bug Sample code

    ToggleSwitch(
                      minWidth: double.infinity,
                      minHeight: MySize.size40,
                      fontSize: 16.0,
                      initialLabelIndex: 0,
                      activeBgColor: [AppTheme.ovaOrange],
                      activeFgColor: Colors.white,
                      inactiveBgColor: AppTheme.ovaGrey,
                      inactiveFgColor: Colors.grey[900],
                      totalSwitches: 2,
                      labels: ['Orders', 'WIP'],
                      onToggle: (index) {
                        print('switched to: $index');
                        setState(() {
                          if(index==0)
                            showOrder=true;
                          else
                            showOrder=false;
    
                        });                  },
                    )
    
    

    the right index is printed but the Active color doesnot change

    opened by Joezzy 4
  • Different width of each switch.

    Different width of each switch.

    Not able to give different width to each button. My tabs name are like "SMS", "Clarification", "Feedback"...but SMS text take up the same space as Clarification, which I don't want

    enhancement complete 
    opened by Shashwat-111 4
  • toogle shitch is not loading properly

    toogle shitch is not loading properly

    I am using the example code but getting this strange effect. Currently, I using this version toggle_switch: ^1.2.0

    ` ToggleSwitch( minWidth: 90.0,

              initialLabelIndex: 1,
              cornerRadius: 20.0,
              activeFgColor: Colors.white,
              inactiveBgColor: Colors.grey,
              inactiveFgColor: Colors.white,
              totalSwitches: 2,
              labels: ['Male', 'Female'],
         
              activeBgColors: [[Colors.blue],[Colors.pink]],
              onToggle: (index) {
                print('switched to: $index');
              },
            ),`
    

    sample

    not a bug 
    opened by akashlilhare 4
  • Added new features.

    Added new features.

    Added option minHeight which when set to null will allow the widget to find its natural size based on the font content. Added option setIndex to allow an user of ToggleSwitch to set its index programatically. Added bool return to onToggle so the toggle could be rejected.

    opened by bsutton 4
  • 0.1.5:

    0.1.5:

    Changelog:

    Added support for disabling the Widget or one or more options it may contain; Added support to determine the colors for the background, text and divider when the widget or its children are disabled.

    opened by rmanenti 4
  • My toggleSwitch doesn't switch and my setstate doesn't work

    My toggleSwitch doesn't switch and my setstate doesn't work

    Describe the bug When I click on the ToggleSwitch, nothing switch, but my index are good when I print it

    To Reproduce

    Column(children: [
            ToggleSwitch(
              minWidth: 100.0,
              initialLabelIndex: showIOSQrcode,
              totalSwitches: 2,
              labels: ['Apple Store', 'Play Store'],
              onToggle: (index) {
                print('switched index: $index');
                setState(() {
                  showIOSQrcode = index;
                });
                print(showIOSQrcode);
              },
            ),
            Padding(padding: EdgeInsets.symmetric(vertical: 5)),
            showIOSQrcode == 0
                ? Image(
                    image: AssetImage(
                        'assets/images/qrcode_ios.png'),
                    width: 180,
                  )
                : Image(
                    image: AssetImage(
                        'assets/images/qr_code_play_store.png'))
            ]),
    

    Expected behavior I expected to see the switch between Apple and Play Store and to see the image change with it

    Additional information

    toggle_switch: ^1.3.0

    [✓] Flutter (Channel unknown, 2.0.6, on macOS 12.0.1 21A559 darwin-arm, locale fr-FR) • Flutter version 2.0.6 at /Users/lucas/Development/flutter • Framework revision 1d9032c7e1 (7 months ago), 2021-04-29 17:37:58 -0700 • Engine revision 05e680e202 • Dart version 2.12.3

    [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3) • Android SDK at /Users/lucas/Library/Android/sdk • Platform android-30, build-tools 30.0.3 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165) • All Android licenses accepted.

    [✓] Xcode - develop for iOS and macOS • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 13.1, Build version 13A1030d • CocoaPods version 1.11.2

    [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

    [✓] Android Studio (version 2020.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)

    [✓] VS Code (version 1.62.3) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.28.0

    [✓] Connected device (2 available) • iPhone Lucas (mobile) • baaa60cd2019dbd8bd0c781818b0fa03815e65c2 • ios • iOS 15.0.2 • Chrome (web) • chrome • web-javascript • Google Chrome 96.0.4664.55

    • No issues found!

    opened by LucaSappey 3
  • Feature Request

    Feature Request

    Hi Pramod, thanks for creating this!

    Just a qtn, can we decide the number of rows?

    Context: I have 2 rows of options for users to choose from. I could do a separate toggle switch for 2 created rows, but I reckon it would be harder to store the printed value as I want them to choose only one choice.

    it would be better if the toggle switch could allow 2 rows in the same widget and they just choose one option and that option is captured.

    Maybe this feature is already out. >.<, and is staring me in the face. Any guidance is appreciated.

    Cheers!

    opened by vegeta-ssaiyan 3
  • Last switch item is always stretched to full width inside CustomScrollView

    Last switch item is always stretched to full width inside CustomScrollView

    Describe the bug When used inside CustomScrollView, last item in the switch always expand to full width.

    To Reproduce

    import 'package:flutter/material.dart';
    import 'package:toggle_switch/toggle_switch.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: CustomScrollView(
              slivers: [
                SliverPadding(
                  padding: const EdgeInsets.only(top: 100),
                  sliver: SliverToBoxAdapter(
                    child: ToggleSwitch(
                      labels: const ['America', 'Canada', 'Mexico'],
                    ),
                  ),
                )
              ],
            ),
          ),
        );
      }
    }
    
    

    Expected behavior It shouldn't stretch the last item

    Screenshots

    simulator_screenshot_BE797BAD-61FA-44B2-92C1-677AE93A17F1

    Additional information

    • toggle_switch version 2.0.1
    opened by khoadng 1
  • Allow Custom Font Style but still respect activeFgColor and inactiveFgColor

    Allow Custom Font Style but still respect activeFgColor and inactiveFgColor

    Is your feature request related to a problem? Please describe. I would like a custom font that changes color on active and inactive.

    Describe the solution you'd like textStyle = widget.customTextStyles!.length == 1 ? widget.customTextStyles![0]! : (widget.customTextStyles!.length > index ~/ 2 && widget.customTextStyles![index ~/ 2] != null ? widget.customTextStyles![index ~/ 2]! : defaultTextStyle);

           change requested:
                  if (active && activeFgColor != null) {
                    textStyle = textStyle.copyWith(color: activeFgColor);
                  } else if (!active && inactiveFgColor != null) {
                    textStyle = textStyle.copyWith(color: inactiveFgColor);
                  }
    

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context Add any other context or screenshots about the feature request here.

    enhancement 
    opened by ryanheitner 1
  • Allow RichTitle or Widget for labels

    Allow RichTitle or Widget for labels

    Hi!

    I need to implement this design: image

    I think with the current lib, I cannot right? Maybe allowing a List for tabs or at least List might get the trick done, what do you think?

    Also maybe I should create a new issue about the possibility of disableling a tab (see my screenshot)?

    Thanks :)

    enhancement 
    opened by baptistesx 1
Releases(v2.0.1)
  • v2.0.1(Apr 15, 2022)

    • Added vertical toggle switch option (PR 51):
      • parameter:
        • isVertical (type bool - default false)
    • Added active borders option (Partial implementation from PR 53):
      • parameter:
        • activeBorders (optional, type List)
      • list with only one Border value will apply that Border to all the active switches
      • different Border values can be provided for different switches
    • Added divider margin option:
      • parameter:
        • dividerMargin (optional, type double - default 8.0)
    • Made totalSwitches parameter optional.
    • Added new changes to customTextStyles:
      • list with only one TextStyle value will apply that TextStyle to all the active switches
    • Added new changes to customWidths:
      • customWidths can now reflect widths greater than device width
      • must use horizontal scroll view to prevent overflow
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Jan 23, 2022)

    • Minor bug fix (PR 44).
      • return null when active switch is de-activated by re-tapping
    • Added changes to fix radiusStyle bug when text direction is set to TextDirection.rtl
      • parameter:
        • textDirectionRTL (optional, type bool - default false)
    • Added custom widths support
      • parameter:
        • customWidths (optional, type List)
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Nov 2, 2021)

    • Added null support for initialLabelIndex (PR 39).
    • Added double tap support to de-select/de-activate active switch (PR 41):
      • parameter:
        • doubleTapDisable (optional, type bool - default false)
    • Added animation duration support:
      • parameter:
        • animationDuration (optional, type int - default 800)
    • Added package test
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Nov 1, 2021)

A Flutter widget that easily adds the flipping animation to any widget

flip_card A component that provides a flip card animation. It could be used for hiding and showing details of a product. How to use import 'package:fl

Bruno Jurković 314 Dec 31, 2022
A widget that allow user resize the widget with drag

Flutter-Resizable-Widget A widget that allow user resize the widget with drag Note: this widget uses Getx Example bandicam.2021-11-11.12-34-41-056.mp4

MohammadAminZamani.afshar 22 Dec 13, 2022
A simple widget for animating a set of images with full custom controls as an alternative to using a GIF file.

image_sequence_animator A simple widget for animating a set of images with full custom controls as an alternative to using a GIF file. If you have a G

AliYigitBireroglu 135 Jan 5, 2023
A draggable Flutter widget that makes implementing a SlidingUpPanel much easier!

sliding_up_panel A draggable Flutter widget that makes implementing a SlidingUpPanel much easier! Based on the Material Design bottom sheet component,

Akshath Jain 1.2k Jan 7, 2023
Circular Reveal Animation as Flutter widget!

Circular Reveal Animation Circular Reveal Animation as Flutter widget! Inspired by Android's ViewAnimationUtils.createCircularReveal(...). Статья с оп

Alexander Zhdanov 48 Aug 15, 2022
A Flutter Package providing Avatar Glow Widget

Avatar Glow This Flutter package provides a Avatar Glow Widget with cool background glowing animation. Live Demo: https://apgapg.github.io/avatar_glow

Ayush P Gupta 250 Dec 22, 2022
✨A clean and lightweight loading/toast widget for Flutter, easy to use without context, support iOS、Android and Web

Flutter EasyLoading English | 简体中文 Live Preview ?? https://nslog11.github.io/flutter_easyloading Installing Add this to your package's pubspec.yaml fi

nslog11 1k Jan 9, 2023
A beautiful animated flutter widget package library. The tab bar will attempt to use your current theme out of the box, however you may want to theme it.

Motion Tab Bar A beautiful animated widget for your Flutter apps Preview: | | Getting Started Add the plugin: dependencies: motion_tab_bar: ^0.1.5 B

Rezaul Islam 237 Nov 15, 2022
a widget provided to the flutter scroll component drop-down refresh and pull up load.

flutter_pulltorefresh Intro a widget provided to the flutter scroll component drop-down refresh and pull up load.support android and ios. If you are C

Jpeng 2.5k Jan 5, 2023
Highly customizable, feature-packed calendar widget for Flutter

TableCalendar Highly customizable, feature-packed calendar widget for Flutter. TableCalendar with custom styles TableCalendar with custom builders Fea

Aleksander Woźniak 1.5k Jan 7, 2023
Flutter 3D Flip Animation Widget

flutter_flip_view This is a flutter Widget base on pure Dart code that provides 3D flip card visuals. Usage add package in your pubspec.yaml dependenc

WosLovesLife 57 Dec 30, 2022
Base Flutter widget which triggers rebuild only of props changed

pure_widget Base widget which triggers rebuild only if props changed Installation pubspec.yaml: dependencies: pure_widget: ^1.0.0 Example import 'da

Andrei Lesnitsky 9 Dec 12, 2022
A Stepper Widget in Flutter using GetX

Stepper Flutter GetX Donate If you found this project helpful or you learned something from the source code and want to thank me, consider buying me a

Ripples Code 0 Nov 27, 2021
A Flutter dropdown widget.

Flutter Dropdown_Below A Flutter Dropdown library which is customize flutter dropdownbutton widget. Options options description type required itemWidt

Denny Hong 27 Sep 7, 2022
Flutter's core Dropdown Button widget with steady dropdown menu and many options you can customize to your needs.

Flutter DropdownButton2 Intro Flutter's core Dropdown Button widget with steady dropdown menu and many options you can customize to your needs. Featur

AHMED ELSAYED 125 Jan 4, 2023
Flutter widget that automatically resizes text to fit perfectly within its bounds.

ONLY FOR FLUTTER WEB Flutter widget that automatically resizes text to fit perfectly within its bounds. Show some ❤️ and star the repo to support the

Rebar Ahmad 4 Jan 6, 2022
Flutter fluid slider - A fluid design slider that works just like the Slider material widget

Fluid Slider for Flutter Inspired by a dribbble by Virgil Pana. A fluid design s

Jay Raj 2 Feb 18, 2022
This flutter package contains a widget called DecodingTextEffect which is having some cool Decode Effects for texts.

This flutter package contains a widget called DecodingTextEffect which is having some cool Decode Effects for texts. Installing 1. Depend on it Add th

Aadarsh Patel 13 Nov 25, 2020
A widget for stacking cards, which users can swipe horizontally and vertically with beautiful animations.

A widget for stacking cards, which users can swipe horizontally and vertically with beautiful animations.

HeavenOSK 97 Jan 6, 2023