gpt4 book ai didi

android - 如何在Android屏幕上显示HTTP请求的异常

转载 作者:行者123 更新时间:2023-12-03 04:35:24 25 4
gpt4 key购买 nike

我使用的是基于Flutter的基本get请求,该请求将发送到RESTful服务器。执行此请求的代码如下:

Future<List<Description>> getTheInfo() async {
List<Description> result;

try {
http.Response resp = await http.get(theUrl + "/home/devices");

if(resp.statusCode == 200) {
var jsonstr = json.decode(resp.body);
var list = jsonstr["devices"] as List;
result = list.map<Description>((json) => Description.fromJson(json)).toList();
}
else {
print('FAILURE: '+resp.statusCode.toString());
}
} catch(exe) {
print('Socket Failure: '+exe.toString());
throw CustomException("FAILURE: ",exe.toString());
}

return(result);
}
自定义异常(exception)是我从下面的Internet上获取的:
class CustomException implements Exception {
final _message;
final _prefix;

CustomException([this._message, this._prefix]);

String toString() {
return "$_prefix$_message";
}
}
我的问题是,尽管我能够将开发环境中发生的任何故障打印到控制台,但无法查看设备上发生的情况。在手机上进行测试时,我发现开发环境中没有出现故障。
我想做的是有一种方法,可以在模拟器的屏幕上(在开发环境中)和实际电话的屏幕上(当我创建要在设备上测试的APK时)显示GET请求引发的异常)。有什么办法可以做到这一点?

最佳答案

不知道您要在这里完成什么,但是有一种优雅的方法可以在UI上显示故障和异常,以使用户知道。在生产应用程序中,这也是一个好习惯。
您需要的是dartz,dartz是一个功能编程包。
使用dartz,您可以使用Either类型返回Future<List<Description>>CustomException这就是它如何适合您的代码。


Future<Either<CustomException,List<Description>>> getTheInfo() async {
List<Description> result;

try {
http.Response resp = await http.get(theUrl + "/home/devices");

if(resp.statusCode == 200) {
var jsonstr = json.decode(resp.body);
var list = jsonstr["devices"] as List;
result = list.map<Description>((json) => Description.fromJson(json)).toList();

return right(result);
}
else {
print('FAILURE: '+resp.statusCode.toString());

return left(CustomException("FAILURE: ",exe.toString()));
}
} catch(exe) {
print('Socket Failure: '+exe.toString());

return left(CustomException("FAILURE: ",exe.toString()));
}
}
在用户界面方面,
...

Widget build(BuildContext context) {

FutureBuilder(
future: getTheInfo(),
builder: (_, AysncSnapshot snapshot) {
if(snapshot.connectionState ==ConnectionStatet.waiting){
return CircularProgressIndicator();
}

snapshot.data.fold(
(l)=> Center(child: Text(l.message), // CustomException message
),
(r)=> Center(child: Text("Success"), // r contains the List<Description>
);
}
}
...

根据成功或失败,您可以呈现适当的窗口小部件。
编辑:
这应该可以工作,但是如果不是BLoc,强烈建议切换到提供者或riverpord

关于android - 如何在Android屏幕上显示HTTP请求的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64181221/

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