Home > Software design >  How to use if else condition in one button with flutter
How to use if else condition in one button with flutter

Time:01-16

I'm building a VPN application with flutter. After users write their server, username, and password they used to click the 'connect' button. But for now, I have two buttons that contain connect and disconnect functions.

connect function:

ElevatedButton(
  child: const Text('Connect'),
  onPressed: () => FlutterVpn.connectIkev2EAP(
    server: _addressController.text,
    username: _usernameController.text,
    password: _passwordController.text,
  ),
),

disconnect function:

ElevatedButton(
  child: const Text('Disconnect'),
  onPressed: () => FlutterVpn.disconnect(),
),

My question is, how to combine those 2 functions above become one button? Thank you in advance for any help.

I've tried this, but it throws me an error.

ElevatedButton(
  onPressed: () async{
    if (state == FlutterVpnState.disconnected){
      child: Text('Connect'),
      FlutterVpn.connectIkev2EAP(
        server: _addressController.text,
        username: _usernameController.text,
        password: _passwordController.text,
      );
    }else{
      child: const Text('Disconnect')
      onPressed: () => FlutterVpn.disconnect();
    }
  }
),

CodePudding user response:

You can do it use ternary expression like checkUp? if true:else for text and if-else conditional statement will work fine and looks better on onPressed.

ElevatedButton(
  onPressed: () async{
    if (state == FlutterVpnState.disconnected){
      FlutterVpn.connectIkev2EAP(
        server: _addressController.text,
        username: _usernameController.text,
        password: _passwordController.text,
      );
    }else{
      FlutterVpn.disconnect();
    }
  },
  child: Text(state == FlutterVpnState.disconnected?'Connect':'Disconnect'),
),

I will recommend you to check conditional-expressions

CodePudding user response:

You can conditionally set the value of Text this way:

Text(state == FlutterVpnState.disconnected ? 'Connect' : 'Disconnect'),
  • Related