Home > database >  Checking if AssetImage asset path exist
Checking if AssetImage asset path exist

Time:02-03

How do I load AssetImage or check if it exists? The data is coming from the api, so I cannot list all the file paths as constants.

As an example path maybe be 'assets/images/${card.imageType}.png' where card.inageType is a variable.

...
child: Image(
       height: 60.0,
       image: Utils.getImage('assets/images/card-${card.category}.png'),
       ),
...

For my getImage function, I tried 2 kinds but not working

Method 1: Using File: The existsSync method is always false. Keep in mind the await async cannot work as the Image widget is expecting not a Future

static dynamic getImage(path) {
    File f = File(path);
    return f.existsSync()
        ? FileImage(f)
        : const AssetImage('assets/images/default.png');
  }
}

Method 2: Using try catch: The exceptions is not being caught

  static AssetImage getImage(path) {
    AssetImage image;

    try {
      image = AssetImage(path);
    } catch (e) {
      image = const AssetImage('assets/images/default.png');
    }

    return image;
  }

CodePudding user response:

You can not use Asset Image for images fetched from Network.

Once you get response from your api. Store the url of the image in a String variable. Usually images from API are stored in a web service.

When you have the url of the image just use NetworkImage widget, example:

SizedBox(
     width: 75,
     height: 75,
     child: userImgUrl.isEmpty
     ? const CircleAvatar(
     child: Text('Avatar'))
     : CircleAvatar(
          radius: 30,
          backgroundImage: NetworkImage(
                             userImgUrl),
                             backgroundColor: Colors.transparent),)

Think userImgUrl is the String that holds the url for the image that can be found on the internet. If image is empty just show a text inside circle avatar. If image is available from API, then show the image inside NetworkImage()

CodePudding user response:

You can check if a file exists asynchronously with this code:

import 'dart:io';
File("path/to/file").exists() 

or checking it synchronously:

import 'dart:io';
File("path/to/file").existsSync()
  •  Tags:  
  • Related