0

How can i prevent the users to accidentally press twice on the button thus placing the same order twice, using debouncing with timer?

I actually tried using debouncing on the button but I couldn't figure it out. Can someone explain it to me how can I achieve this?

I made a Timer? _dobounce in my widget state,

I made a method

void _onButtonPressed() {
if(_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 500),(){

});

}

I am sure this method is not how its supposed to be and I dont know how to use it.

NecSil
  • 1
  • 1
  • You could set the `onPressed` property to `false` after the first click to disable the button. – TijnvdEijnde Aug 23 '23 at 08:02
  • 1
    Does this answer your question? [How to debounce Textfield onChange in Dart?](https://stackoverflow.com/questions/51791501/how-to-debounce-textfield-onchange-in-dart) – Marnix Aug 23 '23 at 08:04
  • Yes and no, I cant figure it out how to use it on the onPressed. – NecSil Aug 23 '23 at 08:33
  • It's best if you can disable the control by setting the action to null while the action is executing. This requires triggering a setState or equivalent. I'll have a video soon that shows that. – Randal Schwartz Aug 23 '23 at 15:50

2 Answers2

0

You can make Debouncer class using Timer

import 'package:flutter/foundation.dart';
import 'dart:async';

class Debouncer {
  final int milliseconds;
  Timer? _timer;

  Debouncer({required this.milliseconds});

  run(VoidCallback action) {
    _timer?.cancel();
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}

Declare it

final _debouncer = Debouncer(milliseconds: 500);

and trigger it

onTextChange(String text) {
  _debouncer.run(() => print(text));
}
Kasun Hasanga
  • 1,626
  • 4
  • 15
  • 35
0

You can create such a class for the debouncing mechanism using Dart's Timer class,

class DeBouncer {
  int? milliseconds;      // The delay time for debouncing in milliseconds
  VoidCallback? action;  // The action to be executed

  static Timer? timer;    // A static Timer instance to manage the debouncing

  static run(VoidCallback action) {
    if (null != timer) {
      timer!.cancel();   // Cancel any previous Timer instance
    }
    timer = Timer(
      const Duration(milliseconds: Duration.millisecondsPerSecond),
      action,            // Schedule the action after a delay
    );
  }
}

To use, wrap you method by DeBouncer.run method

      DeBouncer.run(() {
        /// Call Your method
      });