gpt4 book ai didi

dart - flutter 没有互联网连接时如何读取本地文件?

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

我已经实现了从Internet加载Json的ListView。到现在为止还挺好。
但是我想读取本地文件,以防尝试读取在线json失败。

我有一个异步方法,该方法从互联网或本地 Assets 读取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 Emulator上关闭了网络。

发生的事情是FutureBuilder的快照没有返回任何内容。似乎与流程的执行顺序有关。

这是异常(exception)的屏幕截图: https://ibb.co/iMSRsJ

最佳答案

您错误地使用了asnycawait。使用await时,请勿使用then,因为它们的作用完全相同。检查this out以获取Future的引用。

您还从错误的范围返回,即return都返回到回调而不是函数getPosts。我将用getPostsasync await重写try catch
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);
}
}

关于dart - flutter 没有互联网连接时如何读取本地文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175818/

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