Home > Enterprise >  How to show correct Icon in IconButton Flutter
How to show correct Icon in IconButton Flutter

Time:12-25

I have a button in the AppBar and I want to change its icon on click, but nothing works. If you check the type of the icon inside onPressed, then the condition is triggered depending on which button should be, but it is not displayed.

bool toggle = true;
late Widget searchWidget = IconButton(
  onPressed: (){
    setState(() {
      toggle = !toggle;
    });
  },
  icon: toggle ? const Icon(Icons.search) : const Icon(Icons.cancel),
);    
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      actions: [
        searchWidget,
        ],
      title: searchBar
    ),
    body: displayBody,
    bottomNavigationBar: _bottomMenu,
  );
}

CodePudding user response:

change searchWidget to method to get updated UI,

 Widget searchWidget() => IconButton(
        onPressed: () {
          setState(() {
            toggle = !toggle;
          });
        },
        icon: toggle ? const Icon(Icons.search) : const Icon(Icons.cancel),
      );

And use like

  actions: [
          searchWidget(),
        ],
  • Related