问题
How I can check if a specific asset exists in Flutter. I'm trying to load some images and sound files and I need to handle the case when these assets do not exist.
I need to check the existence because I have audio files and images for numbers from 1 to 1000. When I build my widgets I use a loop from 1 to 1000 to build it. and there are possibilities that the required file ( the image or the sound for the current number ) does not exist in the assets.
回答1:
I assume that you are using the AssetBundle
class to load your data using the load
method which takes ByteData
, and when you use this method, it will throws an exception if the asset is not found.
回答2:
Following Raouf suggestion I handled the case where the assets not exist.
Image loader widget:
Future<Image> _buildImage() async {
String path = "assets/images/contents/${content.id}.jpg";
return rootBundle.load(path).then((value) {
return Image.memory(value.buffer.asUint8List());
}).catchError((_) {
return Image.asset(
"assets/images/null.png",
height: 250.0,
);
});
}
Using the Image widget inside my build method:
FutureBuilder(
future: _buildImage(),
builder: (BuildContext context, AsyncSnapshot<Image> snapshot) {
if (snapshot.connectionState == ConnectionState.done)
return snapshot.data;
else
return Image.asset("assets/images/null.png");
},
),
),
来源:https://stackoverflow.com/questions/52908923/check-if-asset-exist-in-flutter