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!
CodePudding user response:
To check the size of the file, you can
if (File(filepath).lengthSync() != 0)
or
You can await
the file.length()