[英]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.