Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: callback to cancel toggle #77

Merged
merged 2 commits into from Apr 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 18 additions & 14 deletions lib/toggle_switch.dart
Expand Up @@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'dart:math';

typedef OnToggle = void Function(int? index);
typedef CancelToggle = Future<bool> Function(int? index);

// ignore: must_be_immutable
class ToggleSwitch extends StatefulWidget {
Expand Down Expand Up @@ -73,6 +74,9 @@ class ToggleSwitch extends StatefulWidget {
/// OnToggle function
final OnToggle? onToggle;

/// CancelToggle function
final CancelToggle? cancelToggle;

/// Change selection on tap
final bool changeOnTap;

Expand Down Expand Up @@ -121,6 +125,7 @@ class ToggleSwitch extends StatefulWidget {
this.inactiveBgColor,
this.inactiveFgColor,
this.onToggle,
this.cancelToggle,
this.cornerRadius = 8.0,
this.initialLabelIndex = 0,
this.minWidth = 72.0,
Expand Down Expand Up @@ -462,22 +467,21 @@ class _ToggleSwitchState extends State<ToggleSwitch>

/// Handles selection
void _handleOnTap(int index) async {
bool notifyNull = false;
if (widget.changeOnTap) {
if (widget.doubleTapDisable && widget.initialLabelIndex == index) {
setState(() => widget.initialLabelIndex = null);
notifyNull = true;
} else {
setState(() => widget.initialLabelIndex = index);
}
int? newIndex = index;
if (widget.doubleTapDisable && widget.initialLabelIndex == index){
newIndex = null;
}
if (widget.onToggle != null) {
if (notifyNull) {
widget.onToggle!(null);
} else {
widget.onToggle!(index);
}

final cancel = await widget.cancelToggle?.call(newIndex) ?? false;
if(cancel){
return;
}

if (widget.changeOnTap) {
setState(() => widget.initialLabelIndex = newIndex);
}

widget.onToggle?.call(newIndex);
}

/// Calculates width to prevent overflow by taking screen width into account.
Expand Down