Isa*_*aac 34 assets dart flutter
我想要做的是在 Material Widget 中加载图像以在 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...);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,由于我使用的是无状态小部件,因此我必须事先知道图像是否存在,否则我将加载一个空值,对吗?
我对 Futter 很陌生,所以我不知道这是否是一个明显的问题
谢谢!
Nae*_*Nae 58
要查看应用程序的内部本地存储中是否存在文件,请使用:
import 'dart:io' as io;
var syncPath = await path;
// for a file
io.File(syncPath).exists();
// for a directory
io.Directory(syncPath).exists();
Run Code Online (Sandbox Code Playgroud)
Giu*_*oso 16
对我来说只是这样工作:
import 'dart:io';
File("path/to/file").exists()
Run Code Online (Sandbox Code Playgroud)
或者,用于同步检查
import 'dart:io';
File("path/to/file").existsSync()
Run Code Online (Sandbox Code Playgroud)
Ric*_*eap 12
看起来您想尝试ImageProvider从图像可能存在或可能不存在的文件夹中加载一个,然后,如果不存在,则加载后备资产图像(您可以肯定会存在,因为您将它放在根目录中捆)。
尝试这个:
ImageProvider getImageProvider(File f) {
return f.existsSync()
? FileImage(f)
: const AssetImage('images/fallback.png');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34687 次 |
| 最近记录: |