T R*_*T R 10 assets file try-catch dart flutter
在尝试加载数据之前,有没有办法检查Flutter 中是否存在资产文件?
现在我有以下几点:
String data;
try {
data = await rootBundle
.loadString('path/to/file.json');
} catch (Exception) {
print('file not found');
}
Run Code Online (Sandbox Code Playgroud)
问题是,我必须检查文件 1,如果这不存在,我必须检查后备文件(文件 2),如果这也不存在,我加载第三个文件。
我的完整代码如下所示:
try{
//load file 1
} catch (..) {
//file 1 not found
//load file 2
} catch (...) {
//file 2 not found
//load file 3
}
Run Code Online (Sandbox Code Playgroud)
这对我来说看起来很丑陋,但我没有更好的主意......
AssetBundle (作为返回 rootBundle)抽象了加载资产(本地文件、网络)的不同方式,并且没有检查它是否存在的通用方法。
您可以轻松地包装您的加载代码,使其变得不那么“丑陋”。
Future myLoadAsset(String path) async {
try {
return await rootBundle.loadString(path);
} catch(_) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
var assetPaths = ['file1path', 'file2path', 'file3path'];
var asset;
for(var assetPath in assetPaths) {
asset = await myLoadAsset(assetPath);
if(asset != null) {
break;
}
}
if(asset == null) {
throw "Asset and fallback assets couldn't be loaded";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5920 次 |
| 最近记录: |