How to Disable/Enable Button (Elevated, Outline, IconButton) in Flutter App

In this example, we are going to show the way to disable and enable programmatically buttons like Elevated, Outline, IconButton in Flutter Apps. See the example below to disable enable buttons in Flutter.

You need to pass null to onPressed parameter of Buttons in Flutter to disable.

ElevatedButton(
  onPressed: null, 
  child: Text("Elevated Button")
)

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  bool buttonenabled = false; //boolean value to track status of enable and disable, 
                              // false = disable, true = enable

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Enable/Disable Buttons"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        body: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(20),
            child: Column(
              children: [

                ElevatedButton(
                  onPressed: buttonenabled?(){ //if buttonenabled == true then pass a function otherwise pass "null"
                     print("Elevated Button One pressed");
                  }:null, 
                  child: Text("Elevated Button One")
                ),

                OutlinedButton(
                    onPressed: buttonenabled?(){ //if buttonenabled == true then pass a function otherwise pass "null"
                       print("Outline Button Two Pressed");
                    }:null, 
                    child: Text("Outline Button Two")
                ),

                ElevatedButton(  
                  onPressed: (){
                    setState(() { //setState to refresh UI
                        if(buttonenabled){
                            buttonenabled = false;
                            //if buttonenabled == true, then make buttonenabled = false
                        }else{
                            buttonenabled = true;
                            //if buttonenabled == false, then make buttonenabled = true
                        }
                    });
                     
                  },
                  child: Text("Toggle Buttons")
                )

              ],
            )
        )
    );
  }
}

When you press Toogle Buttons, the "enable" status of the above two buttons will change vise versa.

In this way, you can enable or disable Buttons in the Flutter app. 

No any Comments on this Article


Please Wait...