Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter: IconButton onPressed didn't get called

I put a list of widget as action in Scaffold appBar, but they didn't respond when I press them, I have a floatingButton in the scene too and it works perfectly.

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

even if I put IconButton in a Row or Column widget , not in appBar, it doesn't work again.
Answer:
thanks to siva Kumar, I had a mistake in calling function , we should call it in this way:

onPressed: _onSearchButtonPressed, // without parenthesis.

or this way:

onPressed: (){
    _onSearchButtonPressed();
},
like image 406
Mneckoee Avatar asked Feb 26 '18 05:02

Mneckoee


2 Answers

please try with my answer it will work.

    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");
}
like image 66
siva kumar Avatar answered Nov 14 '22 05:11

siva kumar


Bump into the question while searching for other solution.

The answer should be:

onPressed: _onSearchButtonPressed,

Without the () brackets. Since they carry the same signature, there is no need to wrap them around another anonymous / lambda function.

like image 21
s k Avatar answered Nov 14 '22 04:11

s k