File stored in app document directory always exists although it hasn't been created (Flutter)

Issue

I am currently developing a mobile app with flutter and I want to display the profile picture of a user and their friends.
The pictures are stored in Firebase Storage, but to minimize the number of requests I want to load each image once and then store it locally.
I wrote a function to get the image from Firebase storage and store it in the app document directory, but I can’t figure out how to execute the function only when the file doesn’t already exist locally.

This is an excerpt of my code

Future<File?> getProfilePic(String? uid) async {
  Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();

  String filepath = "${appDocumentsDirectory.path}/profiles/$uid.jpg";
  if (await File(filepath).exists()) {
    return File(filepath);
  } else {
    var success = await downloadFromFirebaseAndSaveToLocal(
        "profilepic/$uid.jpg", filepath);
    if (success) {
      getProfilePic(uid);
    }
  }
  return null;
}

Somehow the condition of the if statement (await File(filepath).exists()) is always true. I guess it makes sense. I think the file exists in the directory but doesn’t have any content.

Does anyone know how to check if the file has content?
A normal null check doesn’t work.

Thank you for helping!

Solution

To check the size of the file, you can

if (File(filepath).lengthSync() != 0)

or

You can await the file.length()

Answered By – Ahmed Ashour

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published