SamuelHrmel
SamuelHrmel

Reputation: 181

Flutter - change icon color when selected

I'm trying to make a tab bar and have the icons be gray while selected and go back to black when a different icon is selected. My problem is however that upon clicking on one of icons, it registers the click, but I don't understand why it doesn't change the color of the icons. Help would be greatly appreciated!

int buttonSelected = 1;

IconButton(
  icon: Icon(Icons.home, color: buttonSelected == 1 ? Colors.grey : Colors.black,),
  onPressed: () {
    buttonSelected = 1;
    print('home');},
),

IconButton(
  icon: Icon(Icons.message, color: buttonSelected == 2 ? Colors.grey : Colors.black,),
  onPressed: () {
    buttonSelected = 2;
    print('message');},
),

Upvotes: 0

Views: 2943

Answers (1)

farouk osama
farouk osama

Reputation: 2529

use setState to rebuild page

Make sure you are using statefull widget instead of stateless widget

int buttonSelected = 1;

IconButton(
  icon: Icon(Icons.home, color: buttonSelected == 1 ? Colors.grey : Colors.black,),
  onPressed: () {
    setState(){ buttonSelected = 1;};
    print('home');},
),

IconButton(
  icon: Icon(Icons.message, color: buttonSelected == 2 ? Colors.grey : Colors.black,),
  onPressed: () {
    setState(){ buttonSelected = 2;}; 
    print('message');},
),

Upvotes: 1

Related Questions