flutter: IconButton onPressed didn't get called
Asked Answered
R

3

9

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();
},
Rondeau answered 26/2, 2018 at 5:39 Comment(0)
G
32

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");
}
Goatfish answered 26/2, 2018 at 6:43 Comment(1)
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.Haiduk
G
4

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.

Grogram answered 14/7, 2021 at 0:32 Comment(0)
I
-2

Actually we need to set the VoidCallback for onPressed property, When we tap on icon that VoidCallback is called . We also set null if we don't need any response.

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

We can also directly pass the call back like this

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

Example for null

onPressed: null
Intersperse answered 31/5, 2018 at 6:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.