skip to Main Content

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();
    }
  }
),

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can conditionally set the value of Text this way:

    Text(state == FlutterVpnState.disconnected ? 'Connect' : 'Disconnect'),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search