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



我正在使用一个基本的基于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);
}

自定义例外是我从下面的互联网上获得的:

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()));
}
}

在UI方面,

...
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

最新更新