1 year ago

#377927

test-img

Razvan Andrei

PDF File is not downloading when using Dio in Flutter

I created a Pdf viewer screen and I added a button which should download the PDF from the URL when it's pressed. I display the pdf from an URL, it is displayed correctly but the download function is not working. I tried different examples and implementations found on the internet but nothing worked. Let me know if you have any solution for this. Thanks

This is my dart class:

 class _PdfViewerScreenState extends State<PdfViewerScreen> {
  late PdfViewerController _pdfViewerController;


  String uri = 'https://file-examples.com/wp-content/uploads/2017/10/file-example_PDF_1MB.pdf'; 

  String filename = 'test.pdf'; // file name that you desire to keep

  // downloading logic is handled by this method

  Future<void> downloadFile(uri, fileName) async {

    String savePath = await getFilePath(fileName);

    Dio dio = Dio();

    dio.download(
      uri,
      savePath,
    );
  }

  Future<String> getFilePath(uniqueFileName) async {
    String path = '';

    Directory dir = await getApplicationDocumentsDirectory();
    path = '${dir.path}/$uniqueFileName.pdf';
    return path;
  }

  @override
  void initState() {
    _pdfViewerController = PdfViewerController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var theme = HolidayApp.of(context).theme;
    return Scaffold(
      appBar: AppBar(
          title: Text(
            Constants.downloadRequest,
            style: theme.textTheme.heading3.copyWith(
              fontWeight: FontWeight.w400,
            ),
          ),
          actions: [_downloadButton(downloadFile(uri, filename))]),
      body: SafeArea(
        child: SfPdfViewer.network(
          widget.pdfUrl,
          controller: _pdfViewerController,
        ),
      ),
    );
  }
}

IconButton _downloadButton(Future f) {
  return IconButton(
    icon: const Icon(
      Icons.download,
    ),
    onPressed: () {
      f;
    },
  );
}

android

flutter

dart

pdf

dio

0 Answers

Your Answer

Accepted video resources