dart - 当flutter没有互联网连接时如何读取本地文件?
问题描述
我已经实现了一个从 Internet 加载 Json 的 ListView。到目前为止,一切都很好。但是我想读取一个本地文件,以防尝试读取在线 json 失败。
我有一个从互联网或本地资产读取 json 的异步方法:
Future<List<Post>> getPosts(String urlJsonInternet, String fileJsonLocal) async {
//read json from internet
await http.get(urlJsonInternet).then((responseInternet) {
//If server returns an OK response, parse the JSON
return _buildPostList(responseInternet.body);
}).catchError((onError) {
//read json from local file
rootBundle.loadString(fileJsonLocal).then((responseLocal) {
return _buildPostList(responseLocal);
});
});
}
_buildPostList 它只是一个解析json的方法。
为了测试它,我在 Android 模拟器上关闭了网络。
正在发生的事情是 FutureBuilder 的快照没有返回任何内容。这似乎与流程的执行顺序有关。
这是异常的截图:https ://ibb.co/iMSRsJ
解决方案
你错误地使用asnyc
await
和承诺。使用时await
,您不应该使用,then
因为它们的作用完全相同。看看这个以供参考Future
。
您还从错误的范围返回,即您返回到回调而不是返回到您的函数getPosts。我将用and重写。return
getPosts
async await
try catch
只有在完成后await
才会执行之后的行Future
。更多关于这里。
Future<List<Post>> getPosts(String urlJsonInternet, String fileJsonLocal) async {
try {
//read json from internet
final responseInternet = await http.get(urlJsonInternet);
//If server returns an OK response, parse the JSON
return _buildPostList(responseInternet.body);
} catch (e) {
//read json from local file
final responseLocal = await rootBundle.loadString(fileJsonLocal);
return _buildPostList(responseLocal);
}
}
推荐阅读
- sql - Netsuite 案例声明
- firebase - 如何将匿名帐户链接到 Flutter 中的电话号码?
- ios - NativeScript-Vue 中的分组 UITableView
- c# - ML.NET 显示哪个分数与哪个标签相关
- php - 将两个数组合二为一,数据对应组合
- python - 机器学习损失高的恒定验证精度
- r - r:在 Flexdashboard 中使用 Shiny 渲染 Kable
- django - 在 django 中使用显示在其他页面上的特定图像进行模板渲染时出错
- botframework - 在没有 .bot 文件的情况下配置机器人
- python - 此代码如何比较列表中的数字并输出最大值?