flutter - 抛出异常时,快照会包含错误吗?
问题描述
此方法发送消息并返回Future<bool>
。我的情况是,当状态不是 200 时,快照会包含错误,还是会通过引发异常而使整个应用程序崩溃?
Future<bool> sendMessage(String id, String message) async {
/* sendind logic */
if (r.statusCode == 200) {
return true;
} else {
print('Failed to send message. Status code: ${r.statusCode}');
throw Exception('Failed to send message. Status code: ${r.statusCode}');
}
}
并以这种方式进行
FutureBuilder(
future: result,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Center(child: Text('Success'));
} else if (snapshot.hasError) {
return Center(child: Text("${snapshot.error}"));
}
return kLoading;
},
),
如果方法返回Future<void>
,我应该如何检查 FutureBuilder 是否已完成?
解决方案
AsyncSnapshot是从与异步计算(例如服务器 API 调用、sqlite 数据库调用、shreadpref 调用等)的最新交互中接收到的结果的不可变表示。
snapshot.error
因此,如果最新的计算导致该对象在该字段中也会出现错误(异常) 。所以在你的情况下,代码应该如下所示:
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: result,
builder: (context, snapshot) {
if (snapshot.hasData) {
// Data is avialable. call snapshot.data
}
else if(snapshot.hasError){
// Do error handling
}
else {
// Still Loading. Show progressbar
}
});
}
推荐阅读
- python - 创建列表列表,将列表中的先前值与下一个值连接起来
- javascript - 使用 Ramda.js 求和和排序
- javascript - Vue 3 ref 未更新为模板上的组件
- linux - 如何发送数据/触发以太网网络设备驱动程序的 ndo_start_xmit?
- android - 选择无法在 Android 4.4.4 上运行的联系程序
- php - 当用户未进行选择时,从表单($_GET)在 mysql WHERE 语句中发布结果
- c# - API 请求在 Postman 中有效,但不适用于生成的代码
- swift - 应用偏移量时,CollectionView 单元格 Snapkit 约束失败
- python - 如何创建 rest_framework.request.Request 类型的对象来执行获取请求?
- swagger - Swagger $ref 使用字段名导入文件名