flutter: IconButton onPressed didn't get called

28,472

Solution 1

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

Solution 2

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.

Share:
28,472
Mneckoee
Author by

Mneckoee

Updated on July 24, 2022

Comments

  • Mneckoee
    Mneckoee almost 2 years

    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();
    },
    
  • Rishabh Bhatnagar
    Rishabh Bhatnagar over 3 years
    If possible, try adding an explanation as to why the code posted in the question didn't work and how does your solution mitigate it.