flutter - 当一切正常时出现错误
问题描述
我正在使用 Flutter 构建一个应用程序,您可以在其中将文件添加到应用程序的缓存中。
有两件事不起作用,我不明白为什么。
这是来源
- 每当我第一次启动应用程序(绝对没有缓存)时,我都会收到此错误
目录列表失败,路径 = '/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
首先检查,然后是其他所有内容,但我仍然收到错误消息。
奇怪的是,如果我重新启动该应用程序,它会按预期工作。
有什么解决方案吗?我真的很困惑
解决方案
将您的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;
}
}
推荐阅读
- javascript - 如何将数组作为参数传递给javascript中的函数?
- c# - 将 Outlook 联系人复制和粘贴样式 txt 转换为 C# 对象
- azure - Blazor Azure AD B2C 网络 5 尝试登录时出错
- virtualenv - Conda Environments:如何向系统询问可能的可用环境
- java - 处理 AuthenticationFailureBadCredentialsEvent 后如何返回包含多个字段或响应实体的自定义错误?
- amazon-web-services - 如何从 Lambda 发布到特定的移动推送通知端点?
- python - 哪个字段可以在 django 序列化程序中用于输入带有子网掩码的 ipaddress
- java - 基于Android Dart或Java中的键合并两个对象数组
- python - AttributeError: ''numpy.ndarray' object has no attribute 'rolling'' 仅在过滤 CSV 数据后出现
- python - 使用重新和匹配,我如何从文本文件中搜索和获取某些数据?