首页 > 解决方案 > 当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

标签: dartflutterdart-async

解决方案


你错误地使用asnyc await承诺。使用时await,您不应该使用,then因为它们的作用完全相同。看看这个以供参考Future

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

推荐阅读