downloadImageToLocalCache function

Future<String?> downloadImageToLocalCache(
  1. String imageUrl,
  2. String imageName
)

Download locally the file and return the file path if succes, or null if error.

Implementation

Future<String?> downloadImageToLocalCache(String imageUrl, String imageName) async {
  final tempDir = getTempDir;
  if (tempDir != null) {
    String savePath = "${tempDir.path}/$imageName'";
    try {
      var dio = Dio();
      developer.log('📦 downloading image: $imageUrl');
      final response = await dio.download(imageUrl, savePath);
      if (response.statusCode == 200) {
        return savePath;
      }
      return null;
    } on DioError catch (e) {
      developer.log('❌ Dio Error - image : $imageUrl');
      if (e.type == DioErrorType.response) {
        return null;
      }
      if (e.type == DioErrorType.connectTimeout) {
        return null;
      }
      if (e.type == DioErrorType.receiveTimeout) {
        return null;
      }
      if (e.type == DioErrorType.other) {
        return null;
      }
    } catch (e) {
      developer.log('❌ Error - image : $imageUrl');
    }
  } else {
    developer.log('❌  Temp directory not found!');
  }
  return null;
}