0

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

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

3 回答 3

1

尝试下面的代码

你的按钮

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

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

于 2021-07-29T13:03:14.060 回答
1

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

First one:

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

});
}

Second one:

onPress:()await {
 await YourFunction();
showAlertDialog(context);
    }
于 2021-07-29T13:34:29.823 回答
1

您只需要添加async.onPressed

onPressed: ()async {
               await _makePostRequest();
                showAlertDialog(context);
              },
于 2021-07-29T13:13:58.477 回答