How to use if else condition in a button - flutter

8,493

Instead of having two functions just have one and write your logic inside. like this:

RaisedButton(
  onPressed: () {
    if (priceController.text == "") {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Enter a price"),
            );
          });
    } else {
      apiRequest(url, {'price': priceController.text, 'user_id': "user2"});
    }
  },
  child: Text("Set Level"),
);
Share:
8,493
irongirl
Author by

irongirl

Experienced in Web development using HTML, PHP, CSS. Also, side note: a Mobile App Developer too in Android and iOS. Currently learning about Flutter. Help me out! :)

Updated on December 10, 2022

Comments

  • irongirl
    irongirl over 1 year

    I am trying to show an alert dialog after user has pressed this button after a certain condition is met. if the text is empty it will pop a dialog however using what i tried below, it still pops up the dialog even when text is not empty after pressing button.

    RaisedButton(
                    onPressed: priceController.text == ""
                        ? () => showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                title: Text("Enter a price"),
                              );
                            })
                        : () => apiRequest(url, {
                              'price': priceController.text,
                              'user_id': "user2"
                            }),
                    child: Text("Set Level"),
                  );
    
    • Ferdi
      Ferdi about 5 years
      Indeed it's weird it should work, what about using String.isEmpty method, or refractor you code with an if/else bloc
    • Sami Kanafani
      Sami Kanafani about 5 years
      can you show your full code, maybe you are doing something wrong with the controller?