gpt4 book ai didi

flutter - 如果服务器无法访问,如何显示错误

转载 作者:行者123 更新时间:2023-12-01 23:37:26 27 4
gpt4 key购买 nike

我对 Flutter 还是很陌生。我有一个网络调用要执行。但在此之前,我需要检查设备是否具有互联网连接以及服务器是否可以访问 api 服务器。我已设法检查互联网连接是否可用,但无法显示何时无法访问服务器

这是我到目前为止所做的:

 login(username, password) async {
final String url = "http://10.0.2.2:8080/api/auth/signin"; // iOS
var responseJson;
try {
final response= await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'username': username,
'password': password,
}),
);
responseJson = _response(response);
} on SocketException {
throw FetchDataException('No Internet connection');
}
print(responseJson);
SharedPreferences prefs = await SharedPreferences.getInstance();
var parse = jsonDecode(responseJson.body);

await prefs.setString('username', parse["username"]);
await prefs.setString('message', parse["message"]);
await prefs.setString('accessToken', parse["accessToken"]);

return responseJson;
}
dynamic _response(http.Response response) {
switch (response.statusCode) {
case 200:
var responseJson = json.decode(response.body.toString());
print(responseJson);
return responseJson;
case 400:
throw BadRequestException(response.body.toString());
case 401:

case 403:
throw UnauthorisedException(response.body.toString());
case 500:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response
.statusCode}');
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response
.statusCode}');
}
}

我的登录按钮功能

 RoundedButton(
text: "LOGIN",
press: () async {
if (_formKey.currentState.validate()) {
progressDialog.show();
await login(
username,
password,
);
SharedPreferences prefs =
await SharedPreferences.getInstance();
String token = prefs.getString("accessToken");
print(token);

if (token == null) {
progressDialog.hide();
showAlertsDialog(context);
} else {
showAlertzDialog(context);
}
}
},
)

每当我切换服务器并点击登录时,应用程序就会卡在一个显示登录的进度条上。如何显示没有连接到服务器的警告?

最佳答案

这就是您管理 API 调用的方式。

Future<dynamic> requestGET({String url}) async {
try {
final response = await http.get(Uri.parse(url));
switch (response.statusCode) {
case 200:
case 201:
final result = jsonDecode(response.body);
final jsonResponse = {'success': true, 'response': result};
return jsonResponse;
case 400:
final result = jsonDecode(response.body);
final jsonResponse = {'success': false, 'response': result};
return jsonResponse;
case 401:
final jsonResponse = {
'success': false,
'response': ConstantUtil.UNAUTHORIZED
};
return jsonResponse;
case 500:
case 501:
case 502:
final jsonResponse = {
'success': false,
'response': ConstantUtil.SOMETHING_WRONG
};
return jsonResponse;
default:
final jsonResponse = {
'success': false,
'response': ConstantUtil.SOMETHING_WRONG
};
return jsonResponse;
}
} on SocketException {
final jsonResponse = {
'success': false,
'response': ConstantUtil.NO_INTERNET
};
return jsonResponse;
} on FormatException {
final jsonResponse = {
'success': false,
'response': ConstantUtil.BAD_RESPONSE
};
return jsonResponse;
} on HttpException {
final jsonResponse = {
'success': false,
'response': ConstantUtil.SOMETHING_WRONG //Server not responding
};
return jsonResponse;
}
}

调用这个函数并使用response 我在statefulWidget 的init 方法中调用它。

    @override
void initState() {
// TODO: implement initState
super.initState();

final result = await requestGET('google.com');
if (result['success'] == false) {
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(result['response']),
actions: [
FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.pop(context);
},
),
],
);
;
},
);
}
}

关于flutter - 如果服务器无法访问,如何显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65377295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com