Home > OS >  How to change color in elevatedbutton when it pressed in flutter?
How to change color in elevatedbutton when it pressed in flutter?

Time:01-17

I'm building a VPN application with flutter. After I click connect, the color of the button already change from blue to red. 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.

CodePudding user response:

Try using MaterialStateProperty:

                ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.resolveWith<Color>(
                      (Set<MaterialState> states) {
                        if (states.contains(MaterialState.pressed)) {
                          return Colors.green;
                        }

                        return Colors.red;
                      },
                    ),
                  ),
                ),

CodePudding user response:

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(
  primary: isPressed ? Colors.blue : Colors.redAccent
 ),
),

CodePudding user response:

You need to set a bool for offline and online, then just changed the color based on that bool using theme.

bool colorActive = false;


ElevatedButton(
   style: ElevatedButton.styleFrom(
   backgroundColor:
   colorActive ? Colors.red : Colors.blue,
   elevation: 0,
    ),
   onPressed: () {
     setState((){colorActive = !colorActive;});
        },
    child: SizedBox()),
  • Related