小编典典

如何在Flutter中禁用按钮?

flutter

我刚刚开始了解Flutter,但是我在弄清楚如何设置按钮的启用状态时遇到了麻烦。

从文档中说,设置onPressed为null可禁用按钮,并为其提供值以启用它。如果按钮在生命周期中继续处于相同状态,那就很好。

我得到的印象是,我需要创建一个自定义的有状态小部件,该小部件将允许我以某种方式更新按钮的启用状态(或onPressed回调)。

所以我的问题是我该怎么做?这似乎是一个非常简单的要求,但是我在文档中找不到有关如何执行此操作的任何信息。

Thanks.


阅读 488

收藏
2020-08-13

共1个答案

小编典典

我想你可能要出台一些辅助功能,以build您的按钮
,以及与一些属性键关机的沿有状态的部件。

  • 使用StatefulWidget / State并创建一个变量来保存您的条件(例如isButtonDisabled
  • 最初将其设置为true(如果您要这样做)
    呈现按钮时,请勿将onPressed值直接设置为null某个或某些函数onPressed: () {}
    而是使用三元或辅助函数有条件地设置它(以下示例)
    isButtonDisabled作为此条件的一部分进行检查,并返回一个null或某些函数。
    当按下按钮时(或每当您要禁用按钮时),使用setState(() => isButtonDisabled = true)来翻转条件变量。
  • Flutter将build()使用新状态再次调用该方法,并且按钮将由null按下处理程序呈现并被禁用。

这是使用Flutter计数器项目的更多背景信息。

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _isButtonDisabled;

  @override
  void initState() {
    _isButtonDisabled = false;
  }

  void _incrementCounter() {
    setState(() {
      _isButtonDisabled = true;
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("The App"),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            _buildCounterButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildCounterButton() {
    return new RaisedButton(
      child: new Text(
        _isButtonDisabled ? "Hold on..." : "Increment"
      ),
      onPressed: _isButtonDisabled ? null : _incrementCounter,
    );
  }
}

在此示例中,我使用内联三元有条件地设置Text and onPressed,但是将其提取到
函数中可能更合适(您也可以使用相同的方法来更改按钮的文本):

Widget _buildCounterButton() {
    return new RaisedButton(
      child: new Text(
        _isButtonDisabled ? "Hold on..." : "Increment"
      ),
      onPressed: _counterButtonPress(),
    );
  }

  Function _counterButtonPress() {
    if (_isButtonDisabled) {
      return null;
    } else {
      return () {
        // do anything else you may want to here
        _incrementCounter();
      };
    }
  }
2020-08-13