how can I add two function to a single button? I have a button that sends a request to a server and I would like to add a Dialog after sending the request... I tried this:

onPressed: () {
                _makePostRequest();
                showAlertDialog(context);
              },

But still not working...

The post code:

     _makePostRequest() async {
    final url = Uri.parse('http://127.0.0.1/API');
    final headers = {"Content-type": "application/json"};
    final json = '{"id": "1", "status": "1"}';
    final response = await post(url, headers: headers, body: json);
    final statusCode = response.statusCode;
    final body = response.body;
  }

The Show Dialog code:

    void showAlertDialog(BuildContext context) {
  Widget okButton = TextButton(
    child: Text("OK"),
    onPressed: () {},
  );

  AlertDialog alert = AlertDialog(
    title: Text("PMZ Label Print"),
    content: Text("Label is printing..."),
    actions: [
      okButton,
    ],
  );

  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}


Solution 1: Ravindra S. Patil

Try to below code

Your Button

onPressed:(){
 _makePostRequest();
}

Your API Call

_makePostRequest() async {
final url = Uri.parse('http://127.0.0.1/API');
final headers = {"Content-type": "application/json"};
final json = '{"id": "1", "status": "1"}';
final response = await post(url, headers: headers, body: json);
final statusCode = response.statusCode;
final body = response.body;
//your alert function call
 if (response.statusCode == 200) {
 showAlertDialog(context);

} else {
  print(
    "Error",
   );
 }
}

I have try above code and my code is working


Solution 2: Yeasin Sheikh

you just need to add async on onPressed.

onPressed: ()async {
               await _makePostRequest();
                showAlertDialog(context);
              },


Solution 3: Mohamad Alzabibi

_makePostRequest is of type Future so you can use 2 ways :

First one:

onPress:(){
_makePostRequest().then((v){
 showAlertDialog(context);

});
}

Second one:

onPress:()await {
 await YourFunction();
showAlertDialog(context);
    }