问题描述
如何为单个按钮添加两个功能? 我有一个按钮向服务器发送请求,我想在发送请求后添加一个对话框......我试过这个:
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);
}