在 Function 中添加两个按钮 Flutter

问题描述

如何为单个按钮添加两个功能我有一个按钮向服务器发送请求,我想在发送请求后添加一个对话框......我试过这个:

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

但是还是不行...

邮政编码:

     _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;
  }

显示对话框代码

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

解决方法

试试下面的代码

你的按钮

onPressed:(){
 _makePostRequest();
}

您的 API 调用

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

我已经尝试了上面的代码并且我的代码正在运行

,

您只需要在 async 上添加 onPressed

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

_makePostRequest 是 Future 类型,因此您可以使用两种方式:

First one:

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

});
}

Second one:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...