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;
}