PramodJoshi / toggle_switch

A simple toggle switch widget for Flutter.
https://pub.dev/packages/toggle_switch
MIT License
113 stars 64 forks source link

Option to disable click of toggle event when clicking on same status #59

Closed mayur-holo closed 1 year ago

mayur-holo commented 2 years ago

Current Behaiour! When I am clicking on The same state which the toggle button is, it is firing event.

What should happen? There should be an option to disable event firing on clicking of same toggle button.

PramodJoshi commented 2 years ago

I'll add this to my list of enhancements.

PramodJoshi commented 1 year ago

@mayur-holo Sorry for the delay, just got a chance to look into this. I don't think a new option is needed for this. You can try something like this,

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

void main() => runApp(
      App(),
    );

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyScreen(),
    );
  }
}

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  int currentSwitchIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          margin: EdgeInsets.only(top: 30.0),
          child: ToggleSwitch(
            initialLabelIndex: currentSwitchIndex,
            labels: ['one', 'two'],
            onToggle: (index) {
              /// Only do things if selected switch is different
              if (index! != currentSwitchIndex) {
                print('switched index: $index');
                setState(() {
                  currentSwitchIndex = index;
                },);
              }
            },
          ),
        ),
      ),
    );
  }
}

Screen recording