skip to Main Content

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.

2

Answers


  1. 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));
    }
    
    Login or Signup to reply.
  2. 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
          });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search