saveToDownloadDir static method

Future<bool> saveToDownloadDir({
  1. required List<int> bytes,
  2. required String fileName,
  3. bool addTimestamp = true,
  4. bool requestPermissionStrorage = false,
})

Implementation

static Future<bool> saveToDownloadDir(
    {required List<int> bytes,
    required String fileName,
    bool addTimestamp = true,
    bool requestPermissionStrorage = false}) async {
  try {
    if(requestPermissionStrorage){
      if(!await _requestPermission(Permission.storage)){
        throw EticonDownloadError(error: 'Permission denied');
      }
    }
    if (addTimestamp) {
      String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      int indexOfExtr = fileName.lastIndexOf('.');
      fileName = fileName.substring(0, indexOfExtr) + '_$timestamp' + fileName.substring(indexOfExtr);
    }
    String savePath;
    if (Platform.isIOS || (Platform.isAndroid && (await DeviceInfoPlugin().androidInfo).version.sdkInt! >= 29)) {
      savePath = '${(await path.getApplicationDocumentsDirectory()).path}/$fileName';
    } else {
      savePath = '${(await AndroidPathProvider.downloadsPath)}/$fileName';
    }
    if (savePath.isEmpty) {
      throw EticonDownloadError(error: 'Path to save files is empty');
    }

    File(savePath)
      ..createSync()
      ..writeAsBytesSync(bytes);
    if (Platform.isAndroid && (await DeviceInfoPlugin().androidInfo).version.sdkInt! >= 29) {
      await _channel
          .invokeMethod('downloadFiles', {"fileName": fileName, "mime": mime(fileName), "localPath": savePath});
      File(savePath).deleteSync();
    }
  } catch (error) {
    throw EticonDownloadError(error: 'Problem with saving to downloads directory, error: $error');
  }
  return true;
}