validateImageFile static method
Validate image file (File object)
Returns true if valid, false otherwise with error message
Implementation
static Future<({bool isValid, String? error})> validateImageFile(
File file,
) async {
try {
// Try to check if file exists (may fail on some platforms)
try {
if (!await file.exists()) {
return (isValid: false, error: 'File does not exist');
}
} catch (e) {
// If exists() check fails, continue with other validations
// This can happen on web or iOS where file paths work differently
}
// Try to get file size
int fileSize = 0;
try {
fileSize = await file.length();
} catch (e) {
// If length() fails, try reading bytes to get size
try {
final bytes = await file.readAsBytes();
fileSize = bytes.length;
} catch (e2) {
return (
isValid: false,
error: 'Unable to read file: ${e.toString()}',
);
}
}
const maxSize = 10 * 1024 * 1024; // 10MB
if (fileSize > maxSize) {
return (isValid: false, error: 'File size exceeds 10MB');
}
if (fileSize == 0) {
return (isValid: false, error: 'File is empty');
}
// Check file extension (handle path safely)
try {
final extension = file.path.split('.').last.toLowerCase();
final validExtensions = ['jpg', 'jpeg', 'png', 'heic', 'heif'];
if (!validExtensions.contains(extension)) {
return (
isValid: false,
error:
'Invalid file format. Supported: ${validExtensions.join(", ")}',
);
}
} catch (e) {
// If path access fails, skip extension check but continue
}
return (isValid: true, error: null);
} catch (e) {
return (isValid: false, error: 'Error validating file: ${e.toString()}');
}
}