download function

Future<String> download(
  1. String url
)

Implementation

Future<String> download(String url) async {
  Directory dir;
  if (Platform.isAndroid) {
    dir = (await getExternalStorageDirectory())!;
  } else {
    dir = await getApplicationDocumentsDirectory();
  }

  String filePath;
  Uint8List fileBytes;

  if (url.startsWith("data:")) {
    // Handle data URI
    final uriData = Uri.parse(url);
    final mimeType = uriData.data?.mimeType ?? "application/octet-stream";
    final ext = mimeType.split("/").last;
    final fileName = "file.$ext";
    filePath = "${dir.path}/$fileName";
    fileBytes = uriData.data!.contentAsBytes();

    final file = File(filePath);
    await file.writeAsBytes(fileBytes);
  } else {
    // Handle normal URL with Dio
    final fileName = url.split("?").first.split("/").last;
    filePath = "${dir.path}/$fileName";

    await Dio().download(
      url,
      filePath,
      onReceiveProgress: (received, total) {
        if (total != -1) {
          debugPrint("${(received / total * 100).toStringAsFixed(0)}%");
        }
      },
    );
  }

  return filePath;
}