Home > Back-end >  Check if image exists in folder Flutter
Check if image exists in folder Flutter

Time:12-09

I have tried creating folder in root project named images as well as assets folder with child images like assets/images

on button click i want to check if specific image file exists in folder. i have tried both ways

GestureDetector(
          onTap: () {
            shekitxva = examQuestionList[900].Question;
            // Check if the image exists
            if (File('assets/images/bg.png').existsSync()) {
              print('The image exists in the specified folder.');
            } else {
              print('The image does not exist in the specified folder.');
            }
            setState(() {});
          },
          child: const Text("გაზრდა"),
        ),

File('assets/images/bg.png').existsSync() neither File('images/bg.png').existsSync() seems to work as i always get false

this is my pubspec

flutter:    
uses-material-design: true

assets:
  - images/bg.png
  - assets/
  - assets/images/bg.png    

CodePudding user response:

One way to check image exist or not is that

bool checkImage () {
   try {
      final bundle = DefaultAssetBundle.of(context);
      await bundle.load('assets/images/bg.png');
      AssetImage('assets/images/bg.png');
      return true; /// Exist
   } catch (e) {
        return false; //Not Exist
   )
}

source

CodePudding user response:

The path you pass to the constructor of a file looks for the file on the device, not in the project directory.

Assets you list in your pubspec.yaml file should always exist, but if you want to check whether or not the file exists, use the rootBundle:

Future<bool> assetExists(String path) async {
  try {
    await rootBundle.loadString(path);
    return true;
  } catch (e) {
    return false;
  }
}

CodePudding user response:

thanks Rohan Jariwala

i modified your code and got it working

Future<bool> checkImage() async {
try {
  final bundle = DefaultAssetBundle.of(context);
  await bundle.load('assets/images/bg.png');
  AssetImage('assets/images/bg.png');
  return Future<bool>.value(true);

  /// Exist
} catch (e) {
  return Future<bool>.value(false);
}

}

and then call the function

var value = await checkImage();
print(value);
  • Related