在加载文件之前检查文件是否存在 [英] Check if a file exists before loading it

查看:9
本文介绍了在加载文件之前检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是在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...);
 }
}

所以,因为我使用的是无状态窗口小部件,所以我必须事先知道图像是否存在,否则我会加载一个空的,对吗?

推荐答案

若要查看应用的内部本地存储中是否存在文件,请使用:

import 'dart:io' as io;
var syncPath = await path;
// for a file
io.File(syncPath).exists();
// for a directory
io.Directory(syncPath).exists();

这篇关于在加载文件之前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆