An easy to implement custom switch created for Flutter.

Overview

flutter_switch

All Contributors

pub package pub points popularity likes

An easy to implement custom switch created for Flutter. Give it a custom height and width, border for the switch and toggle, border radius, colors, toggle size, a choice to display an 'On' and 'Off' text and able to add an icon inside the toggle.

GitHub followers

Demo

flutter_switch

Video version: https://youtu.be/JqJnxjE6Efc

Use this package as a library

Add this to your package's pubspec.yaml file:

dependencies:
  flutter_switch: ^0.3.1

You can install packages from the command line with Flutter:

$ flutter pub get

Import in your project:

import 'package:flutter_switch/flutter_switch.dart';

Sample Usage

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool status = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FlutterSwitch Demo"),
      ),
      body: Center(
        child: Container(
          child: FlutterSwitch(
            width: 125.0,
            height: 55.0,
            valueFontSize: 25.0,
            toggleSize: 45.0,
            value: status,
            borderRadius: 30.0,
            padding: 8.0,
            showOnOff: true,
            onToggle: (val) {
              setState(() {
                status = val;
              });
            },
          ),
        ),
      ),
    );
  }
}

Want to Contribute?

Contributions to this project is very much welcome. Let's work together to maintain and improve the project Simply Fork the repository, Commit and Push your changes and create a new Pull Request.

Don't forget to try out the example project under the ./example folder.

Also test your changes by running this command.

$ flutter test

If you have some suggestions, you can reach me at [email protected]

License

BSD 3-Clause License

Copyright (c) 2020, Nichole John Romero
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    3. Neither the name of the copyright holder nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Contributors

Thanks goes to these wonderful people (emoji key):


Nickr

💻 📖 🚧 ⚠️

Lucas Eduardo

💻

Douglas Ramos

💻

Daniyil Yevtyushkin

💻 ⚠️

Maksim Nikolaev

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Comments
  • Fist Switch action is not checking conditions in

    Fist Switch action is not checking conditions in "onToggle"

    I'm checking some conditions before witching the button. But when Switch the button for the first time (ON to OFF or OFF to ON), It is not checking the conditions in onToggle

     child: FlutterSwitch(
              width: 125.0,
              height: 55.0,
              valueFontSize: 25.0,
              toggleSize: 45.0,
              value: value,
              borderRadius: 30.0,
              padding: 8.0,
              showOnOff: true,
              onToggle: (val) {
                if (conditions) {
                  setState(() {
                    this.value = val;
                  });
                } else {
                  setState(() {
                    this.value = !val;
                  });
                }
              },
            ),
    

    Version used

    pubspec.yaml

    flutter_switch: ^0.1.4

    bug 
    opened by savadmv 3
  • Widget Disable Parameter

    Widget Disable Parameter

    I am using this switch in one of the main sections of my app and sometimes, in some occasions, it would be very helpful to be able to disable the flutter_switch until some other parameters or inputs get ready or became available. It looks like there is no property available to disable/enable the flutter_switch widget at the moment and I think it would be great to be able to do so.

    Thanks for your great job.

    enhancement 
    opened by prooshani 2
  • Null Safety

    Null Safety

    Dart 2.12 and Flutter 2 now support sound null safety (https://dart.dev/null-safety). We're using FlutterSwitch and looking to move everything to be null safe. Could you give me an idea of if/when you plan on supporting? Thanks!

    opened by SaintNicholas 2
  • while testing on iOS, in my crashlytics this message is shown every time I use the switch

    while testing on iOS, in my crashlytics this message is shown every time I use the switch

    _FlutterSwitchState#3fb33(ticker active) was disposed with an active Ticker. _FlutterSwitchState created a Ticker via its SingleTickerProviderStateMixin, but at the time dispose() was called on the mixin, that Ticker was still active. The Ticker must be disposed before calling super.dispose(). Tickers used by AnimationControllers should be disposed by calling dispose() on the AnimationController itself. Otherwise, the ticker will leak. The offending ticker was: Ticker(created by _FlutterSwitchState#3fb33(lifecycle state: created)) The stack trace when the Ticker was actually created was: #0 new Ticker.<anonymous closure> (package:flutter/src/scheduler/ticker.dart:67:40) #1 new Ticker (package:flutter/src/scheduler/ticker.dart:69:6) #2 SingleTickerProviderStateMixin.createTicker (package:flutter/src/widgets/ticker_provider.dart:131:15) #3 new AnimationController (package:flutter/src/animation/animation_controller.dart:248:21) #4 _FlutterSwitchState.initState (package:flutter_switch/flutter_switch.dart:44:28) #5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58) #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5) #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #8 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (4 frames) #12 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #13 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (16 frames) #29 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #30 Element.updateChild (package:flutter/src/widgets/framework.dart:3324:20) #31 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16) #32 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:48 <fn>

    duplicate 
    opened by MohitSG96 2
  • Correct dispose of flutter switch widget

    Correct dispose of flutter switch widget

    Hi, first of all, thanks for publishing this package, it is awesome. In a project that I use it, I was getting an exception when I tried to force the widget to rebuilt. The exception was exception: disposed with an active ticker. The solution is to dispose the animation controller, so there you go.

    bug 
    opened by douglasramos 2
  • Added a way to disable the switch.

    Added a way to disable the switch.

    The disabled parameter will accept a value of true or false (default). If disabled, the switch will have a 0.6 opacity.

    FlutterSwitch(
       disabled: true,
       value: status1,
       onToggle: (val) {
           setState(() {
               status1 = val;
           });
        },
    ),
    

    To try out these changes in your own project, depend on this version by putting these lines of code in your pubspec.yaml

    flutter_switch:
        git:
          url: https://github.com/boringdeveloper/FlutterSwitch.git
          ref: 0.3.x
    
    enhancement 
    opened by boringdeveloper 1
  • Changed Icon to Widget

    Changed Icon to Widget

    activeIcon and inactiveIcon expects icons of Icon class. However, I need icons that are images. Therefore, I changed it to expect a widget. Tested and worked for a square image (128x128) containing a circular icon. (with rounded edges cut off)

    opened by woshikie 1
  • check state on app restart

    check state on app restart

    Hi there,

    I can't find any controller to change the switch's state outside the widget. I want to check status of some parameters on app start and then toggle switches respectively without calling the onToggle() call routine, but I can't find any way to do so.

    I would appreciate any suggestion/solution.

    Thanks.

    opened by prooshani 1
  • Switching animation only has 3 frames

    Switching animation only has 3 frames

    I notice the animation is not smooth when I use this widget. then I enable slow animations to observe the animation, I found the animation only has 3 frames. To solve this problem, I changed part of the code to the following figure. image

    It works well for me now.

    opened by jay-lan 1
  • impossible to use with sharedpreference

    impossible to use with sharedpreference

    hello, when I save bool statuts with sharedpreference and I load last value of statut I havn't change...

    For exemple If my last statuts is true, and I load statut at the initStat I this print statuts : true but there is no switch of button...

    bug good first issue 
    opened by nitneuq33000 1
  • Made animation have more than 3 frames, added optional duration and curve properties, centered text

    Made animation have more than 3 frames, added optional duration and curve properties, centered text

    Added optional Duration duration property, to allow developers control the animation's duration better. Didn't change the original value . Added optional Curve curve property, to allow developers control the animation's curve better. Didn't change the original value. Changed Row to Stack. Original Row had 3 fixed frames (left, center, right), but with Stack and Align it will animate position by given animation values (as many frames as possible, no hardcoded frames)

    Also changed the text to be centered.

    opened by Maksim-Nikolaev 0
  • Switch with motion event (Swipe gesture should invoke switch toggle moving)

    Switch with motion event (Swipe gesture should invoke switch toggle moving)

    Hey, first of all I would like to say thank for all of you guys, you did nice job. Really appreciate that!

    The thing I've notice is that: The Switch doesn't move by swipe gesture from left to right and opposite.

    Does the widget have such kind of feature? Maybe I missed that, not sure...

    Anyway, this one should be present I suppose. Are someone doing something like that? I can basically contribute that.

    Thank you

    opened by KirillBorodin 0
  • The image not fill all toggle space

    The image not fill all toggle space

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Steps to reproduce the behavior:

    1. create the switch with active icon = Image.asset.
    2. change toggleColor: Colors.red (to make it more visible)
    3. See error

    Expected behavior The image should be filled and have a fixed height and width (no red color).

    Screenshots image

    Smartphone (please complete the following information):

    • Device: iPhone Xr
    • OS: iOS15

    Additional context Source code:

    return FlutterSwitch(
          value: _currentValue,
          onToggle: (newValue) {
            setState(() {
              _currentValue = newValue;
            });
          },
          height: 30,
          activeIcon: Image.asset(
            'slider-thumb'.pngAssetsPath,
            height: 30,
          ),
          inactiveIcon: Image.asset(
            'slider-thumb'.pngAssetsPath,
            height: 30,
          ),
          toggleColor: Colors.red,
          activeColor: CustomColors.greenIndicator,
          inactiveColor: CustomColors.pinkIndicator,
    );
    

    Thanks

    opened by caokietbk 0
  • Custom Text Switch with custom shape toggle might be  good

    Custom Text Switch with custom shape toggle might be good

    Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

    Describe the solution you'd like A clear and concise description of what you want to happen.

    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.

    opened by Nabinda 0
  • Reduce padding between toggle and edges to 0

    Reduce padding between toggle and edges to 0

    I am trying to create a switch like in this image: image

    However, I cannot find a way to reduce the distance between the toggle and the edges to 0. It ends up looking like this: image

    It would be nice if there was a setting that allows to remove this little bit of padding.

    I have already looked at the code and by subtracting 9 from the Container width on line 382 I get the following: image

    This is certainly better, but the 9 is hardcoded for my specific toggle size.

    opened by Perondas 0
  • size is not properly manage by default

    size is not properly manage by default

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Steps to reproduce the behavior:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    Screenshots If applicable, add screenshots to help explain your problem.

    Desktop (please complete the following information):

    • OS: [e.g. iOS]
    • Browser [e.g. chrome, safari]
    • Version [e.g. 22]

    Smartphone (please complete the following information):

    • Device: [e.g. iPhone6]
    • OS: [e.g. iOS8.1]
    • Browser [e.g. stock browser, safari]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    opened by parth1964 1
Releases(v0.3.0)
  • v0.3.0(Mar 16, 2021)

    This release features a null-safety flutter_switch. Please be careful with breaking changes. An additional disabled parameter is added. It expects a true or false (default) value.

    Source code(tar.gz)
    Source code(zip)
Beautiful Custom Switch package created with Flutter

custom_switch Beautiful Custom Switch package created with Flutter. The source code is 100% Dart, and everything resides in the /lib folder. Show some

Mohak Gupta 55 Sep 6, 2022
This is a repository for Flutter Focused Menu, an easy to implement package for adding Focused Long Press Menu to Flutter Applications

Focused Menu This is an easy to implement package for adding Focused Long Press Menu to Flutter Applications Current Features Add Focused Menu to Any

Paras Jain 160 Dec 26, 2022
The XOR Encryption algorithm is a effective and easy to implement method of symmetric encryption.

Symmetric XOR cipher library About XOR cipher XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method,

Plague Fox 7 Apr 20, 2022
A beautiful switch made with Flutter

Crazy Switch Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flut

Pedro Massango 50 Nov 20, 2022
Flutter Xlive Switch

xlive_switch A Xlive Switcher plugin for Flutter Getting Started This plugin is based on Oleg Frolov's animation design which I found on Dribbble: htt

Châu Minh Phúc 15 Nov 4, 2022
Daynightswitch - A day night switch widget for Flutter.

DayNightSwitch A day night switch widget for Flutter. Installation Add to pubspec.yaml. dependencies: day_night_switch: Usage To use plugin, just i

Divyanshu Bhargava 103 Oct 25, 2022
Building a simple Flutter app * Switch Theme * for understanding the BLoC State Management including: Cubit Communications with StreamSubscription & Managing Route.

Building a simple Flutter app * Switch Theme * for understanding the BLoC State Management including: Cubit Communications with StreamSubscription & Managing Route.

TAD 1 Oct 3, 2022
An interesting and practical switch component.

FSwitch An interesting and practical switch component. Supports setting tips, slider decorations, shadows, and good interaction. Author:Newton(coorchi

Fliggy Mobile 81 Dec 13, 2022
Declaratively switch child widgets based on the current `Router` location.

Features Declaratively switch child widgets based on the current Router location. class SideBar extends StatelessWidget { Widget build(_){ re

gskinner team 7 Dec 12, 2022
A smart switch for you.

Features A smart switch for you.

Narendra Bhatt 2 Aug 26, 2022
best flutter / dart practices + Custom Painter + Sliver App Bar + Custom Scrollview

Weekly Budget Flutter App A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get yo

Mohamed Awnallah 4 Oct 21, 2021
A customizable carousel slider widget in Flutter which supports inifinte scrolling, auto scrolling, custom child widget, custom animations and built-in indicators.

flutter_carousel_widget A customizable carousel slider widget in Flutter. Features Infinite Scroll Custom Child Widget Auto Play Horizontal and Vertic

NIKHIL RAJPUT 7 Nov 26, 2022
Flutter package that provides you custom clippers to help you achieve various custom shapes.

flutter_custom_clippers Flutter package that provides you custom clippers to help you achieve various custom shapes. Usage To use this plugin, add flu

Damodar Lohani 291 Dec 23, 2022
FT-Custom-Widget - A Custom Widget Built With Flutter

Custom Widget Watch it on YouTube Product Screen Sample when you implement compl

Firgia 5 Mar 29, 2022
A customizable carousel slider for Flutter. Supports infinite sliding, custom indicators, and custom animations with many pre-built indicators and animations.

Flutter Carousel Slider A customizable carousel slider for flutter Screenshots Installing dependencies: flutter_carousel_slider: ^1.0.8 Demo Demo a

Udara Wanasinghe 23 Nov 6, 2022
Flutter custom carousel slider - A carousel slider widget,support custom decoration suitable for news and blog

flutter_custom_carousel_slider A carousel slider Flutter widget, supports custom

Emre 40 Dec 29, 2022
An easy way to show a flutter custom popup widget.

flutter_easy_popup An easy way to show a flutter custom popup widget. Screenshot Example Screenshot Dropdown Menu App Operation Guide Multi Highlights

BakerJ 42 Oct 26, 2022
A library that makes it easy for you to create your own custom wizard.

Flutter Wizard Author: Jop Middelkamp A library that makes it easy for you to create your custom wizard. You'll have 100% control over the appearance

Baseflow 13 Dec 2, 2022
MindInventory 15 Sep 5, 2022