downloadFile method

Future<File?> downloadFile(
  1. String url, {
  2. required String savePath,
  3. dynamic onProgress(
    1. int
    )?,
})

Implementation

Future<File?> downloadFile(String url,
    {required String savePath, Function(int)? onProgress}) async {
  try {
    File file = File(savePath);
    if (file.existsSync()) {
      file.deleteSync();
    }
    if (!file.parent.existsSync()) {
      file.parent.createSync(recursive: true);
    }
    Response response = await dioInstance.get(
      url,
      onReceiveProgress: (received, total) {
        final p = (received / total * 100).toInt();
        onProgress?.call(p);
      },
      options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
          validateStatus: (status) {
            return status == 200;
          }),
    );
    var raf = file.openSync(mode: FileMode.write);
    raf.writeFromSync(response.data);
    await raf.close();
    return file.existsSync() ? file : null;
  } catch (e) {
    'download file $url error:$e'.logMx();
    return null;
  }
}