How to Enable/Disable an ElevatedButton in Flutter

Viewed 13649

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,
    );
     }
    }
5 Answers

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;
});
onPressed: () {
   if (isDisabled == true) { return; }

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

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.

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,
Related