Reputation: 1536
What I want to do is load an image in a Material Widget to use it in a ListTile, but this asset might not exist.
class MyImage extends StatelessWidget {
final imagePath;
MyIcon(String iconName) {
try { // check if imagePath exists. Here is the problem
imagePath = check('assets/$iconName.png/');
} catch (e, s) { // if not
imagePath = 'assets/$iconName.png/';
}
}
@override
Widget build(BuildContext context) {
return Material(...here I will load the imagePath...);
}
}
So, since I'm using a Stateless widget, I have to know beforehand if the image exists, otherwise I'll load a null right?
Upvotes: 78
Views: 89661
Reputation: 15335
In order to see whether or not a file exists in internal local storage of the app use:
import 'dart:io' as io;
var syncPath = await path;
// for a file
await io.File(syncPath).exists();
io.File(syncPath).existsSync();
// for a directory
await io.Directory(syncPath).exists();
io.Directory(syncPath).existsSync();
Upvotes: 113
Reputation: 25
In order to see whether or not a file exists in local storage (as with image.network) now you can use :
Image.file(File("path/to/file"),
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {return Text('file access error');
Upvotes: -3
Reputation: 647
For me simply worked this:
import 'dart:io';
File("path/to/file").exists()
or, for checking it synchronously
import 'dart:io';
File("path/to/file").existsSync()
Upvotes: 44
Reputation: 51702
Looks like you want to try to load an ImageProvider
from a folder where the image may or may not exist and then, if it does not, load a fallback asset image (which you can be sure will exist as you'll put it in your root bundle).
Try this:
ImageProvider getImageProvider(File f) {
return f.existsSync()
? FileImage(f)
: const AssetImage('images/fallback.png');
}
Upvotes: 17