【问题标题】:flutter: IconButton onPressed didn't get called颤动:IconButton onPressed 没有被调用
【发布时间】:2018-02-26 05:39:45
【问题描述】:

我在Scaffold appBar 中放置了一个小部件列表作为操作,但是当我按下它们时它们没有响应,我在场景中也有一个floatingButton,它运行良好。

appBar: new AppBar(
        title: new Text(
            widget.title,
          style: new TextStyle(
            fontFamily: 'vazir'
          ),
        ),
        centerTitle: true,
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.search),
            highlightColor: Colors.pink,
            onPressed: _onSearchButtonPressed(),
          ),
        ],
      ),

void _onSearchButtonPressed() {
    print("search button clicked");
  }

即使我将 IconButton 放在 RowColumn 小部件中,而不是放在 appBar 中,它也无法再次工作。
答案:
感谢 siva Kumar,我在调用函数时出错了,我们应该这样调用它:

onPressed: _onSearchButtonPressed, // without parenthesis.

或者这样:

onPressed: (){
    _onSearchButtonPressed();
},

【问题讨论】:

    标签: android ios click flutter


    【解决方案1】:

    请尝试我的答案,它会起作用。

        appBar: new AppBar(
        title: new Text(
            widget.title,
          style: new TextStyle(
            fontFamily: 'vazir'
          ),
        ),
        centerTitle: true,
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.search),
            highlightColor: Colors.pink,
            onPressed: (){_onSearchButtonPressed();},
          ),
        ],
      ),
    
    void _onSearchButtonPressed() {
    print("search button clicked");
    }
    

    【讨论】:

    • 如果可能,请尝试添加解释,说明问题中发布的代码为何不起作用以及您的解决方案如何缓解它。
    【解决方案2】:

    在寻找其他解决方案时遇到问题。

    答案应该是:

    onPressed: _onSearchButtonPressed,
    

    没有 () 括号。由于它们具有相同的签名,因此无需将它们包装在另一个匿名 / lambda 函数中。

    【讨论】:

      【解决方案3】:

      实际上我们需要为onPressed属性设置VoidCallback,当我们点击图标时,就会调用VoidCallback。 如果我们不需要任何响应,我们也会设置 null。

      class PracticeApp extends StatelessWidget {
      Widget build(BuildContext context) {
      return new Scaffold(
           floatingActionButton: new FloatingActionButton(
           tooltip: "Add",
           child: new Icon(Icons.add),
           onPressed: () { setState(); },
          ),
        );
       }
      }
      
      void setState() {
        print("Button Press");
      }
      

      我们也可以像这样直接回调

      onPressed: () { setState(() { _volume *= 1.1; }); }
      

      null 的示例

      onPressed: null
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-16
        • 2021-05-19
        • 2021-12-02
        • 2020-12-12
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        相关资源
        最近更新 更多