'Flutter Web download file from url instead of opening it

Is there any way to get files like .pdf downloaded directly on user's device instead of opening this pdf in the browser? This code works for downloading non browser supported files but it opens pdf, mp3, etc. in the browser.

final anchor = AnchorElement(
    href: pickedFile)
  ..setAttribute("download", fileName)
    ..click();


Solution 1:[1]

If someone is still searching for solution.Here is what I have done.

Anchor tag will directly download file if it has download attribute.

Note: Download attribute is only supported for same-origin request

So instead of assigning external URL link to anchor element. Create Blob object from PDF data and create Object URL from that.

 var url = Url.createObjectUrlFromBlob(Blob([data]));
      AnchorElement(href: url)
        ..setAttribute('download', '<downloaded_file_name.pdf>')
        ..click();

I am using Firebase to store file so here is the complete code.

FirebaseStorage.instance.ref(resumeFileName).getData().then(
    (data) {
      var url = Url.createObjectUrlFromBlob(Blob([data]));
      AnchorElement(href: url)
        ..setAttribute('download', '<downloaded_file_name.pdf>')
        ..click();
    }
  );

Solution 2:[2]

Use Dio Library.

dependencies:
  dio: ^3.0.10

to download file

response = await dio.download("https://www.google.com/", "./xx.html");

this video will help you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akshay
Solution 2 Tharaka Dayanjana