[英]How to change color in elevatedbutton when it pressed in flutter?
I'm building a VPN application with flutter. After I click connect, the color of the button already change from blue to red.我正在使用 flutter 构建一个 VPN 应用程序。单击连接后,按钮的颜色已经从蓝色变为红色。 But when I click disconnect, the color of the button didn't turn back to blue.但是当我点击断开连接时,按钮的颜色并没有变回蓝色。
This is my code:这是我的代码:
bool isPressed = true;
ElevatedButton(
onPressed: () async {
if (state == FlutterVpnState.disconnected) {
FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
);
setState(() {
isPressed = !isPressed;
},
);
}
if (state == FlutterVpnState.connected) {
FlutterVpn.disconnect();
}
if (state == FlutterVpnState.error) {
FlutterVpn.disconnect();
}
},
child: Text(
state == FlutterVpnState.disconnected? 'Connect' : 'Disconnect',
),
style: ElevatedButton.styleFrom(
primary: isPressed ? Colors.blue : Colors.redAccent
),
),
My question is how to turn back the color to blue?我的问题是如何将颜色变回蓝色? Thank you in advance for any help.预先感谢您的任何帮助。
You need to set a bool for offline and online, then just changed the color based on that bool using theme.您需要为离线和在线设置一个布尔值,然后使用主题根据该布尔值更改颜色。
bool isPressed = true;
ElevatedButton(
onPressed: () async {
if (state == FlutterVpnState.disconnected) {
FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
);
setState(() {
isPressed = true;
},
);
}
if (state == FlutterVpnState.connected) {
FlutterVpn.disconnect();
setState(() {
isPressed = false;
},
}
if (state == FlutterVpnState.error) {
FlutterVpn.disconnect();
setState(() {
isPressed = false;
},
}
},
child: Text(
state == FlutterVpnState.disconnected? 'Connect' : 'Disconnect',
),
style: ElevatedButton.styleFrom(
primary: isPressed ? Colors.blue : Colors.redAccent
),
),
Try using MaterialStateProperty
:尝试使用MaterialStateProperty
:
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return Colors.green;
}
return Colors.red;
},
),
),
),
try with this code.尝试使用此代码。
bool isConnected = false;
ElevatedButton(
onPressed: () async {
if (state == FlutterVpnState.disconnected) {
FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
);
isConnected = true;
}
if (state == FlutterVpnState.connected) {
FlutterVpn.disconnect();
isConnected = false;
}
if (state == FlutterVpnState.error) {
FlutterVpn.disconnect();
isConnected = false;
}
setState(() {});
},
child: Text(
state == FlutterVpnState.disconnected? 'Connect' : 'Disconnect',
),
style: ElevatedButton.styleFrom(
backgroundColor: isPressed ? Colors.blue : Colors.redAccent
),
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.