Flutter:IconButton onPressed 没有被调用

9

我在ScaffoldappBar中将一组小部件作为操作项添加,但当我点击它们时,它们没有响应。同时,场景中还有一个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 放在 Row 或 Column widget 中,而不是放在 appBar 中,它仍然无法正常工作。
回答:
感谢 siva Kumar,在调用函数时我犯了一个错误,我们应该以这种方式调用它:
onPressed: _onSearchButtonPressed, // without parenthesis.

或者使用这种方式:
onPressed: (){
    _onSearchButtonPressed();
},
3个回答

32

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

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

4
如果可能的话,请尝试解释一下为什么问题中发布的代码无法正常工作,以及您的解决方案如何缓解这个问题。 - Rishabh Bhatnagar

4
在寻找其他解决方案时遇到了这个问题。
答案应该是:
onPressed: _onSearchButtonPressed,

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


-2
实际上,我们需要为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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接