首页 > 解决方案 > 当一切正常时出现错误

问题描述

我正在使用 Flutter 构建一个应用程序,您可以在其中将文件添加到应用程序的缓存中。

有两件事不起作用,我不明白为什么。

这是来源

  1. 每当我第一次启动应用程序(绝对没有缓存)时,我都会收到此错误

目录列表失败,路径 = '/data/user/0/com.example.lockedapp/cache/file_picker/'(操作系统错误:没有这样的文件或目录,errno = 2)

即使我在尝试显示目录​​之前已采取预防措施来创建目录。

  bool checkFilesEmpty() {
    
    var cache = new Directory('/data/user/0/com.example.lockedapp/cache/file_picker');
  
    cache.exists().then((resp) => { if (!resp) { cache.create() } }); // creates a new cache directory if it does not exist

    return cache.listSync(recursive: false).toList().length != 0; // returns false if it's empty
}

在第 31 行,checkFilesEmpty首先检查,然后是其他所有内容,但我仍然收到错误消息。

奇怪的是,如果我重新启动该应用程序,它会按预期工作。

有什么解决方案吗?我真的很困惑

标签: flutteroopdart

解决方案


将您的checkFilesEmpty放在 Stateful 小部件的 initState 方法中,因此它将在您的小部件构建之前被调用。

class MyHomeState extends State<MyHome> {
  bool filesEmpty;
    @override
    void initState() {
        super.initState();
        filesEmpty = checkFilesEmpty();
    }
.
. // Your rest of code
.
}

您可以将导致错误的语句放在 try catch 块中。如果没有列表,那么您可以在 catch 块中创建一个:

  bool checkFilesEmpty() { 
    try{
      var cache = new Directory('/data/user/0/com.example.lockedapp/cache/file_picker');
      return cache.listSync(recursive: false).toList().length != 0; 
    }
    catch{
        cache = Directory('/data/user/0/com.example.lockedapp/cache/file_picker').create() ;
        return cache.listSync(recursive: false).toList().length != 0; 
    }
}

推荐阅读