rurjaf
rurjaf

Reputation: 60

How to use if else condition in one button with flutter

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

Upvotes: 0

Views: 178

Answers (2)

krishnaacharyaa
krishnaacharyaa

Reputation: 24912

You can conditionally set the value of Text this way:

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

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63559

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

Upvotes: 2

Related Questions