我正在写一个用于酒店注册的应用程序,在这里我要发送如下的发帖请求
checkNetworkConnection仅用于检查设备上是否存在活动连接的ID,如果为true,则我调用 postFormData 方法
Future<dynamic> checkNetworkConnection() async {
try {
final result = await InternetAddress.lookup("www.google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
postFormData().then((val) {
if (jsonDecode(val.body)[0]["response"] == "false") {
setState(() {
isLoading = false;
//isAbsorbing = false;
});
print(val.body);
print("something went wrong");
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text("hello"),
content: Text("something went wrong"),
),
);
} else if (jsonDecode(val.body)[0]["response"] == "true") {
setState(() {
isLoading = false;
//isAbsorbing = false;
});
print(val.body);
print("hotel added successfully");
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text("Hotel Added Successfully"),
content: Text("Hey there! Welcome to j1"),
));
}
}).catchError((error) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) {
return new AlertDialog(
title: Text("error!"), content: Text(error.toString()));
});
});
}
} on SocketException catch (_) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text(
"Connection Error !",
style: TextStyle(
color: Colors.redAccent, fontWeight: FontWeight.bold),
),
content: Text("Check your internet connection !"),
));
}
}
postFormData方法如下所示
Future<dynamic> postFormData() async {
//there are declarations for parent and headers I just excluded them because they were quite a lot ^_^ !
final response = await http
.post("https://thej1.app/apiDataReq",
body: parent, headers: httpHeaders)
.then((val) => val)
.timeout(Duration(seconds: 5))
.catchError((_) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) =>
new AlertDialog(title: Text("error"), content: Text("error")));
});
return response;
}
还有其他相同的做法吗?和未来的建设者一样? 我的响应主体具有一个结构,因此我可以创建响应模型。但是我可以将其隐含在将来的构建器中。此外,我还希望捕获异常和超时错误。
感谢进阶!