urlToFile static method

Future<File> urlToFile(
  1. String imageUrl
)

Downloads an image from a URL and saves it to local storage as a File.

Downloads an image from the provided URL and saves it to the appropriate directory based on the platform (Downloads folder on Android, App Documents on iOS). Generates a unique filename using random number and timestamp.

Parameters:

  • imageUrl: The URL of the image to download

Returns a File object pointing to the saved image, or an empty File('') on failure.

Platform-specific behavior:

  • Android: Saves to Downloads directory (no permission required)
  • iOS: Requests storage permission, saves to Application Documents directory

The generated filename format is: dish_{random}. {timestamp}.png where random is 0-99 and timestamp is milliseconds since epoch.

Example:

final imageFile = await RtCommonFunction.urlToFile(
  'https://example.com/image.jpg'
);

if (imageFile.path.isNotEmpty) {
  print('Image saved to: ${imageFile.path}');
} else {
  print('Failed to download image');
}

Possible failure cases:

  • Network errors during download
  • HTTP response status code != 200
  • Permission denied on iOS
  • File system errors

All errors are logged to debug console using debugPrint.

Implementation

static Future<File> urlToFile(String imageUrl) async {
  var rng = Random();
  if (Platform.isAndroid) {
    try {
      GetConnect getConnect = GetConnect();

      final response = await getConnect.httpClient.get(imageUrl);
      if (response.statusCode == 200) {
        final appDocDir = await getDownloadsDirectory();
        final file = File(
            '${appDocDir!.path}/dish_${rng.nextInt(100)}.${DateTime.now().millisecondsSinceEpoch}.png');
        await file.writeAsBytes(response.body);
        debugPrint('Image downloaded and saved to ${file.path}');
        return file;
      } else {
        debugPrint('Failed to download image: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error downloading image: $e');
    }
  } else {
    final status = await Permission.storage.request();
    if (status.isGranted) {
      try {
        GetConnect getConnect = GetConnect();
        final response = await getConnect.httpClient.get(imageUrl);
        if (response.statusCode == 200) {
          final appDocDir = await getApplicationDocumentsDirectory();
          final file = File(
              '${appDocDir.path}/dish_${rng.nextInt(100)}.${DateTime.now().millisecondsSinceEpoch}.png');
          await file.writeAsBytes(response.body);
          debugPrint('Image downloaded and saved to ${file.path}');
          return file;
        } else {
          debugPrint('Failed to download image: ${response.statusCode}');
        }
      } catch (e) {
        debugPrint('Error downloading image: $e');
      }
    } else {
      debugPrint('Permission denied to access storage.');
    }
  }
  return File('');
}