Adrian Smith
Adrian Smith

Reputation: 1073

How to Enable/Disable an ElevatedButton in Flutter

Does anybody know how to enable/disable a Flutter ElevatedButton? I've reviewed the documentation but I can't see anything that is obvious.

class IcoButton extends StatelessWidget {
    IcoButton(
      {@required this.lbl,
      @required this.col,
      @required this.ico,
      @required this.onPress});

  final String lbl;
  final FaIcon ico;
  final MaterialColor col;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton.icon(
      label: Text(lbl),
      icon: ico,
      style: ElevatedButton.styleFrom(
        primary: col,
        onPrimary: Colors.white,
        minimumSize: Size(160.0, 60.0),
        textStyle: TextStyle(
          fontSize: 24,
        ),
      ),
      onPressed: onPress,
    );
     }
    }

Upvotes: 20

Views: 32194

Answers (5)

Kalex
Kalex

Reputation: 356

As others have pointed out, setting the onPressed callback to null will deactivate the button for you.

Note however that it is the callback itself that must be null, not its return, so like this:

onPressed: null,

And not like this

onPressed: () => null,

Upvotes: 10

Onur İnci
Onur İnci

Reputation: 116

onPressed: () {
   if (isDisabled == true) { return; }

    setState(() { int a = 10; });
}

Upvotes: 0

spmno
spmno

Reputation: 845

I use a member variable "_isDisable" to enable button or not. Put below code in the build function to init the view:

ElevatedButton(
  onPressed: _isDisable? null : callBackFunction,
  child: Text("submit"),
  style: ButtonStyle(),
);

when you want to disable button, call

setState(() {
  _isDisable = true;
});

when you want to enable button, call

setState(() {
  _isDisable = false;
});

Upvotes: 21

Adrian Smith
Adrian Smith

Reputation: 1073

The proper way to do it is by passing null to the onPress callback as @Shannon and @ASAD HAMEED have mentioned. However, the AbsorbPointer widget is also worth a look.

Upvotes: 0

Shannon
Shannon

Reputation: 914

Passing null to the onPressed callback will disable the button.

If onPressed and onLongPress callbacks are null, then the button will be disabled.

https://api.flutter.dev/flutter/material/ElevatedButton-class.html

Upvotes: 40

Related Questions