[英]How to change background color of button in flutter when selected?
問題的圖像如下
在此處輸入圖像描述SizedBox(width: MediaQuery.of(context).size.width * 0.46, child: ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))), backgroundColor: MaterialStateProperty.resolveWith( (Set states) { if (states.contains(MaterialState.pressed)) { return Colors.red; } else { return Colors.white; } }, ), //背景顏色高度:MaterialStateall.5 ), //定義高程 shadowColor: MaterialStateProperty.all( Colors.grey), //定義 shadowColor ), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext Context) => const community( ))); }, child: const Text('COMMUNITY', style: TextStyle(color: Colors.grey))), )
確保您使用的是有狀態小部件。 使一個 boolean 值為 isSelected(默認為 False),並且每當按下按鈕時 setState 將 isSelected 設置為 true。 現在 go 回到按鈕顏色並使用三元運算符。
isSelected? (New Color) : (Default Color)
這是我的示例代碼。
Container(
padding: EdgeInsets.symmetric(horizontal: 2, vertical: 2),
decoration: BoxDecoration(
border: Border.all(
color: foodtype == 'Veg' ? Colors.green : Colors.red,
),
),
child: Icon(
Icons.circle,
color:
foodtype == 'Veg' ? Color.fromARGB(255, 31, 177, 36) : Colors.red,
),
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.