Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

dart - Check if asset exist in flutter

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");
          },
        ),
      ),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...