downloadImage static method

Future<String?> downloadImage(
  1. String url, {
  2. Duration timeout = defaultTimeout,
})

Downloads an image from url and returns the local file path.

Images are cached locally to avoid repeated downloads. If download fails or times out, returns null.

Parameters:

  • url: The URL of the image to download
  • timeout: Maximum time to wait for download (default: 10 seconds)

Example:

final imagePath = await NotificationImageLoader.downloadImage(
  'https://example.com/image.jpg',
);
if (imagePath != null) {
  print('Image cached at: $imagePath');
}

Implementation

static Future<String?> downloadImage(
  String url, {
  Duration timeout = defaultTimeout,
}) async {
  if (kIsWeb) {
    // Web doesn't support local file storage for notifications
    logi('Image download not supported on web');
    return null;
  }

  try {
    // Check if image is already cached
    final cachedPath = await _getCachedImagePath(url);
    if (cachedPath != null) {
      logi('Using cached image: $cachedPath');
      return cachedPath;
    }

    logi('Downloading notification image: $url');

    // Download the image with timeout
    final response = await http.get(Uri.parse(url)).timeout(timeout);

    if (response.statusCode != 200) {
      loge('Failed to download image: HTTP ${response.statusCode}', url);
      return null;
    }

    // Determine file extension from URL or content type
    final extension = _getImageExtension(url, response.headers['content-type']);

    // Save to cache directory
    final filePath = await _saveToCache(url, response.bodyBytes, extension);

    logi('Image downloaded and cached: $filePath');
    return filePath;
  } catch (e, stackTrace) {
    loge(e, 'Error downloading notification image', stackTrace);
    return null;
  }
}