How to avoid multiple button click at same time in flutter

How to Avoid Multiple Button Click at the Same Time in Flutter

In Flutter, to avoid multiple button clicks at the same time, you can disable the button after it is clicked and enable it again after a certain period of time or when the asynchronous operation tied to the button is complete. Here’s an example that demonstrates this approach:

  
import 'package:flutter/material.dart';

class AvoidMultipleClicksButton extends StatefulWidget {
  @override
  _AvoidMultipleClicksButtonState createState() => _AvoidMultipleClicksButtonState();
}

class _AvoidMultipleClicksButtonState extends State {
  bool _isButtonDisabled = false;

  void _handleButtonClick() {
    if (!_isButtonDisabled) {
      setState(() {
        _isButtonDisabled = true;
      });

      // Make an API call or perform any asynchronous operation here
      // ...

      // Simulating a delay of 2 seconds
      Future.delayed(Duration(seconds: 2), () {
        setState(() {
          _isButtonDisabled = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text("Click me"),
      onPressed: _isButtonDisabled ? null : _handleButtonClick,
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text("Avoid Multiple Button Clicks"),
      ),
      body: Center(
        child: AvoidMultipleClicksButton(),
      ),
    ),
  ));
}
  
  

In the above example, we have a custom button called “AvoidMultipleClicksButton”. Inside its state, we have a boolean variable “_isButtonDisabled” which tracks whether the button is disabled or not. Initially, the button is enabled. When the button is clicked, we disable it and perform any asynchronous operation (e.g., making an API call, saving data to the database, etc). After the operation is complete, we re-enable the button.

To disable the button, we set its “onPressed” property to null. This prevents any further clicks until the button is re-enabled. Once the button is re-enabled, its “onPressed” property is set to the corresponding click handler function (“_handleButtonClick” in this case).

In this example, we simulate an API call by using the “Future.delayed” function with a duration of 2 seconds. You can replace this with your actual asynchronous operation. When the duration is over, we enable the button again by setting “_isButtonDisabled” to false. This updates the UI and enables the button for subsequent clicks.

In the Flutter app’s “main” function, we create an instance of “AvoidMultipleClicksButton” and place it inside a “Center” widget, which is further wrapped by a “Scaffold” widget to create a basic app layout. The button is displayed inside an “AppBar” at the top of the screen.

By implementing this approach, you can prevent multiple button clicks at the same time in Flutter.

Leave a comment