Bill Tertis
Bill Tertis

Reputation: 207

How to download a file on flutter?

How to download a .pdf file from an URL with POST Request having headers in Flutter?

i have a different pdf files for each user and i want the link to be different depend on the user.

Upvotes: 0

Views: 1543

Answers (1)

Nijat Namazzade
Nijat Namazzade

Reputation: 742

You can use flutter_downloader plugin for downloading your files.

dependencies:
  flutter_downloader: ^1.8.4

And also you can use this codebase for that:

import 'dart:io';
import 'dart:ui';
import 'package:fimber/fimber.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class DownloadingService {
  static const downloadingPortName = 'downloading';

  static Future<void> createDownloadTask(String url) async {
    final _storagePermission = await _permissionGranted();
    Fimber.d('Current storage permission: $_storagePermission');

    if (!_storagePermission) {
      final _status = await Permission.storage.request();
      if (!_status.isGranted) {
        Fimber.d('Permission wasnt granted. Cancelling downloading');
        return;
      }
    }

    final _path = await _getPath();
    Fimber.d('Downloading path $_path');

    if (_path == null) {
      Fimber.d('Got empty path. Cannot start downloading');
      return;
    }

    final taskId = await FlutterDownloader.enqueue(
        url: url,
        savedDir: _path,
        showNotification: true,
        // show download progress in status bar (for Android)
        openFileFromNotification: true,
        // click on notification to open downloaded file (for Android)
        saveInPublicStorage: true);

    await Future.delayed(const Duration(seconds: 1));

    if (taskId != null) {
      await FlutterDownloader.open(taskId: taskId);
    }
  }

  static Future<bool> _permissionGranted() async {
    return await Permission.storage.isGranted;
  }

  static Future<String?> _getPath() async {
    if (Platform.isAndroid) {
      final _externalDir = await getExternalStorageDirectory();
      return _externalDir?.path;
    }

    return (await getApplicationDocumentsDirectory()).absolute.path;
  }

  static downloadingCallBack(id, status, progress) {
    final _sendPort = IsolateNameServer.lookupPortByName(downloadingPortName);

    if (_sendPort != null) {
      _sendPort.send([id, status, progress]);
    } else {
      Fimber.e('SendPort is null. Cannot find isolate $downloadingPortName');
    }
  }
}

And in another page you can use this class to download your file:

final _receivePort = ReceivePort();

  @override
  void initState() {
    super.initState();
    IsolateNameServer.registerPortWithName(
        _receivePort.sendPort, DownloadingService.downloadingPortName);
    FlutterDownloader.registerCallback(DownloadingService.downloadingCallBack);
    _receivePort.listen((message) {
      Fimber.d('Got message from port: $message');
    });
  }

  @override
  void dispose() {
    _receivePort.close();
    super.dispose();
  }

 void _downloadFile() async {
    
      try {
        await DownloadingService.createDownloadTask(url.toString());
      } catch (e) {
        print("error")
      }
  
  }

Upvotes: 1

Related Questions