【问题标题】:Flutter: How to change button depending on state?Flutter:如何根据状态更改按钮?
【发布时间】:2021-09-22 11:49:08
【问题描述】:

我正在尝试执行以下操作:我有一个容器,其中有一个按钮,单击按钮 (onPressed) 后,我想显示一个不同的按钮(也就是更改小部件)。

在此过程中将不胜感激,在此先感谢!

【问题讨论】:

  • 那么到目前为止,您可以做什么,究竟在哪里卡住了?
  • @someJoe121 检查我的答案。你可以达到你想要的结果

标签: flutter dart


【解决方案1】:

例如定义初始值

double paddingLeft = 10.0;

点击该按钮后,用实际值更新状态就像

setState(() {
  paddingLeft = 20.0
});

【讨论】:

    【解决方案2】:

    可能有不同的方法。其中一种方法是:

    bool _val = true;
    
    Container(
      child: _val ? button1(    // when _val is true button1 will be the child of container. So it will be visible.
          onPressed: () {
            _val = !_val;
            setState(() {
             });
           }) 
              : button2(),     // when _val is false button2 will be the child of container. So it will be visible.
    );
    

    【讨论】:

      【解决方案3】:

      首先,您需要确保您所在的类扩展了StatefulWidget,因为这意味着当状态更改时该类将重新呈现,这就是您需要能够显示另一个按钮的原因。

      然后你可以定义一个状态bool _showButton1 = true;

      在你的容器中你可以有这样的东西:

      Container(
        child: _showButton1 ? _button1() : _button2();
      )
      

      (含义:如果_showButton1为真,则显示小部件_button1,否则显示_button2)

      _button1 看起来像这样:

      Widget _button1() {
        return Button(
          onPressed: () => setState(() {
             _showButton1 = false;
          })
        );
      }
      

      (意思:当这个按钮被按下时,将_showButton1的状态更新为false并重新渲染这个类-->按钮2会显示出来)

      【讨论】:

        猜你喜欢
        • 2021-01-17
        • 2015-06-10
        • 2014-08-30
        • 2019-11-30
        • 2017-05-12
        • 2021-07-19
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多