How to Prevent Button Double Tap in Flutter

The sample Google flutter code below illustrate how to prevent button double tap in flutter.

Depending on the use case, you disable a button click to prevent double tap or you can use a counter to check how many times a button has been tapped.

Here, we will disable the button so that it will not receive any tap.

The code is based on flutter version 1.0.0

Main.dart (App entry point)

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      //home: MyHomePage(title: 'Flutter Demo Home Page'),
      home: PreventDoubleTap(),
    );
  }
}
prevent_double_tap.dart
import 'package:flutter/material.dart';

class PreventDoubleTap extends StatefulWidget {
  @override
  PreventDoubleTapState createState() {
    return new PreventDoubleTapState();
  }
}

class PreventDoubleTapState extends State<PreventDoubleTap> {
  //boolean value to determine whetherbutton is tapped
  bool _isButtonTapped = false;

  _onTapped() {
    setState(() => _isButtonTapped =
        !_isButtonTapped); //tapping the button once, disables the button from being tapped again
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Prevent Double Tap'),
      ),
      body: Center(
        child: RaisedButton(
          color: Colors.red,
          child: Text('Tap Once'),
          onPressed: _isButtonTapped
              ? null
              : _onTapped, //if button hasnt being tapped, allow user tapped. else, dont allow
        ),
      ),
    );
  }
}

 

flutter button double tap

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment