如何在Flutter中禁用按钮?

如何在Flutter中禁用按钮?,第1张

如何在Flutter中禁用按钮

我想你可能要出台一些辅助功能,以

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();      };    }  }


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4897732.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存