【发布时间】:2020-02-28 12:25:24
【问题描述】:
我为我工作的公司做了一个应用程序,该应用程序可以运行并解决了一些问题,但是代码很乱,因为我不是正式的程序员,这是我的第一个应用程序。现在我正在尝试改进代码。
这里的问题是我不知道如何检查http post是否成功。
在下面的代码中,您可以看到我进行了一些错误处理,但它无法正常工作。 例如,如果应用程序没有从服务器收到“ok”消息,它将返回一个错误,但如果互联网不工作,它不会返回错误,因为它将永远尝试发送帖子。 我想始终检查帖子是否成功并通知用户,或者在尝试一段时间后显示错误(比如 2 秒,我不知道),解决这个问题的最佳方法是什么?
欢迎任何其他改进代码的提示。
if ((_usuarioController.text.isEmpty) ||
(_placaController.text.isEmpty) ||
(_boxController.text.isEmpty) ||
(dropdownValue1 == "Vehicle type")) {
Toast.show(
"\n Complete all fields \n",
context,
duration: Toast.LENGTH_LONG,
gravity: Toast.CENTER,
backgroundRadius: 5.0,
);
} else if (_pecasList.length < 1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Empty List"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
}),
]);
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Send the items?"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
}),
new FlatButton(
child: new Text("Send"),
onPressed: () async {
Map<String, dynamic> newDados = Map();
newDados["usuario"] = _usuarioController.text.trimLeft();
newDados["placa"] = _placaController.text.trimLeft();
newDados["box"] = _boxController.text.trimLeft();
newDados["tipo_veiculo"] = dropdownValue1;
_dadosList.add(newDados);
print(_pecasList + _dadosList);
Map<String, String> headers = new Map<String, String>();
headers["Content-type"] = "application/json";
headers["Accept"] = "application/json";
//String str = '{"take":55, "skip":"0"}';
final resp = await http.post('http://' + ipServidor,
body: jsonEncode(_dadosList +
_pecasList), //+ jsonEncode(_pecasList),
headers: headers);
print(resp.statusCode);
_dadosList
.clear(); //Cleans the list
print(resp.body);
if (resp.statusCode == 200) {
if (resp.body == "ok") {
setState(() {
print(_pecasList);
_pecasList.clear();
_placaController.clear();
_boxController.clear();
dropdownValue1 = "Vehicle type";
Navigator.of(context).pop();
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(
"Error"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
}),
]);
});
}
} else {
print("communication error");
Navigator.of(context).pop();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("communication error"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
}),
]);
});
}
})
],
);
},
);
}
}```
【问题讨论】:
标签: android flutter httprequest