使用 Flutter 动态加载资源
我正在运行一个 Flutter 应用程序,其中需要显示一个产品列表。
我有一个资产文件夹(在 pubspec.yaml 中加载),其中包含我的某些产品图像。
如果不存在,我不想显示图像或占位符
尝试一:
Image buildImg() {
var img = `assets/img/${product.id}.png`;
if(File(img).existsSync()){
return Image.asset(img);
}else{
return Image.asset('assets/img/placeholder.png');
}
}
结果:条件始终为假
尝试二:
Image buildImg() async {
try{
var img = rootBundle.load(`assets/img/${product.id}.png`);
return Image.memory(img.buffer.asUint8List());
}catch (_){
return Image.asset('assets/img/placeholder.png');
}
}
结果:工作正常,但终端中出现很多警告。
有没有更好的方法来动态加载资源?谢谢
I'm running a Flutter application with a list of products need to be displayed.
I've an asset folders (loaded in pubspec.yaml) which contains certain of my product images.
I wan't to show the image or a placeholder if not exists
Attempt one :
Image buildImg() {
var img = `assets/img/${product.id}.png`;
if(File(img).existsSync()){
return Image.asset(img);
}else{
return Image.asset('assets/img/placeholder.png');
}
}
Result: condition is always false
Attempt two :
Image buildImg() async {
try{
var img = rootBundle.load(`assets/img/${product.id}.png`);
return Image.memory(img.buffer.asUint8List());
}catch (_){
return Image.asset('assets/img/placeholder.png');
}
}
Result: Working but a lot of warns in terminal.
Is there a better way to dynamically load assets ? Thank's
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
图像小部件有一个错误生成器,当提供的路径无效时会调用该错误生成器,
只需使用此代码
the Image widget has an error builder which is called when the provided path is not valid,
simply use this code