Flutter IO Dev
Flutter IO Dev

Reputation: 2147

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.

Upvotes: 4

Views: 10895

Answers (4)

AlexF1
AlexF1

Reputation: 385

you can try my solution, if you use a simple Image.asset Widget:

Image.asset(
'assets/image.jpg',
 errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
                return Image.network('path');})

Upvotes: 5

Rodrigo porras
Rodrigo porras

Reputation: 236

For someone that Flutter IO Dev answer did not work because the exception still appears, this worked for me:

Future<Widget> getDevIcon(String path) async {
  try {
    await rootBundle.load(path);
    return Image.asset(path);
  } catch (_) {
    return SizedBox.shrink();
  }
}

Upvotes: 1

Raouf Rahiche
Raouf Rahiche

Reputation: 31356

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.

Upvotes: 3

Flutter IO Dev
Flutter IO Dev

Reputation: 2147

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

Upvotes: 3

Related Questions