dart - 在加载文件之前检查文件是否存在
问题描述
我想要做的是在材质小部件中加载图像以在 ListTile 中使用它,但该资产可能不存在。
class MyImage extends StatelessWidget {
final imagePath;
MyIcon(String iconName) {
try { // check if imagePath exists. Here is the problem
imagePath = check('assets/$iconName.png/');
} catch (e, s) { // if not
imagePath = 'assets/$iconName.png/';
}
}
@override
Widget build(BuildContext context) {
return Material(...here I will load the imagePath...);
}
}
所以,因为我使用的是无状态小部件,所以我必须事先知道图像是否存在,否则我会加载一个 null 对吗?
解决方案
要查看应用程序的内部本地存储中是否存在文件,请使用:
import 'dart:io' as io;
var syncPath = await path;
// for a file
io.File(syncPath).exists();
// for a directory
io.Directory(syncPath).exists();