如何在没有网络连接的情况下读取本地文件?
How to read local file when there is no internet connection on flutter?
我实现了一个 ListView,它从 Internet 加载 Json。到目前为止,一切都很好。
但我想读取本地文件以防尝试读取在线 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
,因为它们的作用完全相同。检查 this out 以供参考 Future
。
您还 returning 来自 错误的范围 ,即您的两个 return
return 到 回调 而不是你的函数 getPosts。我将用 async await
和 try catch
.
重写 getPosts
await
之后的行只有在 Future
完成后才会执行。 More on that here.
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);
}
}
我实现了一个 ListView,它从 Internet 加载 Json。到目前为止,一切都很好。 但我想读取本地文件以防尝试读取在线 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
,因为它们的作用完全相同。检查 this out 以供参考 Future
。
您还 returning 来自 错误的范围 ,即您的两个 return
return 到 回调 而不是你的函数 getPosts。我将用 async await
和 try catch
.
getPosts
await
之后的行只有在 Future
完成后才会执行。 More on that here.
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);
}
}