[英]Flutter - change icon color when selected
我正在嘗試制作一個標簽欄,並在選擇時將圖標變為灰色,並在選擇不同的圖標時變回黑色。 然而,我的問題是,在單擊其中一個圖標時,它會注冊點擊,但我不明白為什么它不會改變圖標的顏色。 幫助將不勝感激!
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');},
),
使用setState
重建頁面
確保您使用的是有狀態小部件而不是無狀態小部件
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');},
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.