未处理的异常:在flutter中下载文件时,在反压后在dispose()之后调用setState()

时间:2020-01-29 13:33:15

标签: flutter dio

我正在使用dio插件来快速下载文件并在小部件中显示下载进度,同时在当前下载屏幕上进行反压,而出现异常

Unhandled Exception: setState() called after dispose(): _FileDownloadCardState#537ff(lifecycle state: defunct, not mounted)

这是我的代码,并进行了一些文件验证

Future<void> downloadFile(OfflineMapFile offlineMapFile) async {
    if(offlineMapFile.isDownloading) {
      return;
    }
    Directory fileDir;
    try {
      offlineMapFile.isDownloading = true;
      Dio dio = Dio();
      Directory dir = await UAAppContext.getInstance().appDir;
      //todo: need to test on ios
      fileDir = await new Directory(dir.path + offlineMapFile.fileStoragePath).create();
      await dio.download(
          offlineMapFile.fileUrl, "${fileDir.path}/${offlineMapFile.fileName}",
          onReceiveProgress: (received, total) {
            if (total != -1) {
              print("Rec: $received , Total: $total");
              debugPrint("Directory path : " +
                  offlineMapFile.fileStoragePath +
                  "/" +
                  offlineMapFile.fileName);
              setState(() {
                offlineMapFile.isDownloading = true;
                offlineMapFile.isDownloaded = false;
                downloadProgressString = ((received / total) * 100).toStringAsFixed(0) + "%";
              });
            }
          });
    } catch (e) {
      print(e);
      setState(() {
        offlineMapFile.isDownloading = false;
        offlineMapFile.isDownloaded = false;});

    } finally {
      // TODO Check whether the files are downloaded or not! Validation
      // And set state accordingly.
      setState(() {
        //TODO change boolean as per the file Validation
        offlineMapFile.isDownloading = false;
        offlineMapFile.isDownloaded = true;
        downloadProgressString = "Completed";

        if(offlineMapFile.fileName.contains(".zip") && fileDir != null){
          CommonUtils.unzipFile(fileDir.path +"/"+ offlineMapFile.fileName, fileDir.path + "/Offline/");
        }

      });
      print("Download completed");
    }
  }

1 个答案:

答案 0 :(得分:1)

您要在未安装的小部件上调用setState,要解决此问题,您只需添加此条件

if(mounted) {
  setState(//....
}