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

问题描述 投票:0回答:1

我已经实现了一个从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的Snapshot没有返回任何内容。它似乎与进程的执行顺序有关。

这是例外的截图:https://ibb.co/iMSRsJ

dart flutter dart-async
1个回答
0
投票

你正在错误地使用asnyc await和承诺。当使用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);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.