onPressed不禁用按钮

时间:2020-01-21 21:44:55

标签: flutter flutter-layout

我试图在this article中实施该解决方案,但对我而言不起作用。当我单击按钮时,应将其禁用。另外,当我单击按钮并热重新加载该应用程序时,它将使按钮变为禁用状态。

我也尝试使用函数,但是访问小部件变量时遇到困难。

bool _isButtonDisabled = false;
MaterialButton(
  color: Colors.blue,
  textColor: Colors.white,
  disabledColor: Colors.grey,
  disabledTextColor: Colors.black,
  child: Text('Login'),
  shape: RoundedRectangleBorder(
      borderRadius: new BorderRadius.circular(4)),
  onPressed: _isButtonDisabled ? null : () async {
    _isButtonDisabled = true;

    // Login Stuff
  }
)

1 个答案:

答案 0 :(得分:3)

要将更改应用于用户界面,您需要在setState()方法内进行

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

完整示例:


class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool _isButtonDisabled = false;

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      color: Colors.blue,
      textColor: Colors.white,
      disabledColor: Colors.grey,
      disabledTextColor: Colors.black,
      child: Text('Login'),
      shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(4)),
      onPressed: _isButtonDisabled
          ? null
          : () async {
              setState(() {
                _isButtonDisabled = true;
              });

              // Login Stuff
            },
    );
  }
}