How to disable or make button invisible in flutter
How to disable or make button invisible in flutter

Hi, Guys Welcome to Proto Coders Point, In this fluter tutorial we will learn how to disable a button in flutter & also learn how to make flutter raisedbutton invisibility when not in use so that we can prevent a button from being clicked twice accidentally.

Preventing a button from being clicked twice accidentally

Sometimes what happens is when a user wants to submit a form or perform an action when a button is clicked but accidentally a submit button or flutter raisedbutton gets clicked twice, due to flutter button getting clicked double-time accidentally, double data entry get stored or user perform task twice or face some problem while using your flutter app.

So to prevent this you need to disable further onClick event on button, until the task or the process get completed.

How to enable/disable a button in a flutter – OnClick disable button

Step to follow to enable/disable a button in flutter app.

Video Tutorial

1. Create a boolean variable isButtonClickable

Under StatefullWidget create a boolean variable that we can use to check if button is disabled or enabled.

bool isButtonClickable = true;

initially, as per your app requirement you can keep it either to true or false, in my case i am keep it to true.

2. Create a flutter button ( ElevatedButton) with onPressed property

In the below Snippet Widget Button Code, Depending on the value of isButtonClickable, I am setting text to button either Clickable or Not Clickable,

Then in onPressed() i am using if statement to check if button is Enabled, if Enabled then call the method to perform action/task else do nothing.

ElevatedButton(
              onPressed: () {
                if (isButtonClickable) {
                  ButtonClicked();
                }
              },
              child: Text(
                isButtonClickable?"Clickable":"Not Clickable",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),

3. Create a method/function which perform some task.

Then, when a button is pressed, the method/function is called, in which by using Flutter State Management (setState()), I am updating isButtonClickable to false, Which make button disable.

That means now user will not be able to click button again twice by mistake.

NOTE: Just, for Example, I am using Future.delayed to make isButtonClickable = true after certain duration (seconds), so that it can be clickable after some time.

In your case as per your project, you can perform an action like, for example, a data is getting submitted to the database & depending on server response (success) you can clean the form and enable button or simply navigate the user to another flutter page.

Note: you may also show a circular progress indicator during a process

  void ButtonClicked() async {

    Duration time = Duration(seconds: 5);

    setState(() {
      isButtonClickable = false;                     //make the button disable to making variable false.
      print("Clicked Once");

      Future.delayed(time,(){
        setState(() {
          isButtonClickable = true;                    //future delayed to change the button back to clickable
        });

      });
    });
  }

4. [Optional] Make Button Invisible

If you want to make the button invisible, until any task or process is getting performed you can simply wrap the ElevatedButton Widget with the Visibility widget and use the visible property & set it to true or false.

Visibility(
              visible: isButtonClickable,
              child: ElevatedButton(
                onPressed: () {
                  if (isButtonClickable) {
                    ButtonClicked();
                  }
                },
                child: Text(
                  isButtonClickable?"Clickable":"Not Clickable",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
  ),

Complete Source Code – onClick disable button flutter

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:assets_audio_player/assets_audio_player.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ButtonDisable(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  late AnimationController
      iconController; // make sure u have flutter sdk > 2.12.0 (null safety)

  bool isAnimated = false;
  bool showPlay = true;
  bool shopPause = false;

  AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    iconController = AnimationController(
        vsync: this, duration: Duration(milliseconds: 1000));

    audioPlayer.open(Audio('assets/sound/bobbyrichards.mp3'),
        autoStart: false, showNotification: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Playing Audio File Flutter"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.network(
                "https://i.pinimg.com/originals/f7/3a/5b/f73a5b4b7262440684a2b5c39e684304.jpg",
                width: 300,
              ),
              SizedBox(
                height: 30,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  InkWell(
                    child: Icon(CupertinoIcons.backward_fill),
                    onTap: () {
                      audioPlayer.seekBy(Duration(seconds: -10));
                    },
                  ),
                  GestureDetector(
                    onTap: () {
                      AnimateIcon();
                    },
                    child: AnimatedIcon(
                      icon: AnimatedIcons.play_pause,
                      progress: iconController,
                      size: 50,
                      color: Colors.black,
                    ),
                  ),
                  InkWell(
                    child: Icon(CupertinoIcons.forward_fill),
                    onTap: () {
                      audioPlayer.seekBy(Duration(seconds: 10));
                      audioPlayer.seek(Duration(seconds: 10));
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  void AnimateIcon() {
    setState(() {
      isAnimated = !isAnimated;

      if (isAnimated) {
        iconController.forward();
        audioPlayer.play();
      } else {
        iconController.reverse();
        audioPlayer.pause();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    iconController.dispose();
    audioPlayer.dispose();
    super.dispose();
  }
}

class ButtonDisable extends StatefulWidget {
  @override
  _ButtonDisableState createState() => _ButtonDisableState();
}

class _ButtonDisableState extends State<ButtonDisable> {
  bool isButtonClickable = true;

  void ButtonClicked() async {
    Duration time = Duration(seconds: 5);
    setState(() {
      isButtonClickable = false;
      print("Clicked Once");

      Future.delayed(time,(){
        setState(() {
          isButtonClickable = true;
        });

      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Visibility(
              visible: isButtonClickable,
              child: ElevatedButton(
                onPressed: () {
                  if (isButtonClickable) {
                    ButtonClicked();
                  }
                },
                child: Text(
                  isButtonClickable?"Clickable":"Not Clickable",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}