Home > OS >  Flutter download a file from url automatically to downloads directory
Flutter download a file from url automatically to downloads directory

Time:06-08

Is there a way or a package in Flutter that downloads a file directly to downloads folder for Android and iOS from a direct URL for example: https://******/image.jpg, without any user overhead just a click and download..

CodePudding user response:

You can use Dio package to download any file.

A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

Example

import 'package:dio/dio.dart';
var dio = Dio();
response = await dio.download('https://******/image.jpg');

CodePudding user response:

Yes use following packages to completely achieve it :

dio: ^4.0.0
path_provider: ^2.0.2
permission_handler: ^8.0.0 2

then use following code :

define variables:

late String _localPath;
late bool _permissionReady;
late TargetPlatform? platform;

get device platform in initState()

@override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      platform = TargetPlatform.android;
    } else {
      platform = TargetPlatform.iOS;
    }
  }

for check and requesting device's permissions :

  Future<bool> _checkPermission() async {
    if (platform == TargetPlatform.android) {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

prepare for finding localpath :

Future<void> _prepareSaveDir() async {
    _localPath = (await _findLocalPath())!;

    print(_localPath);
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async {
    if (platform == TargetPlatform.android) {
      return "/sdcard/download/";
    } else {
      var directory = await getApplicationDocumentsDirectory();
      return directory.path   Platform.pathSeparator   'Download';
    }
  }

and at last for downloading file:

InkWell(
        onTap: () async {
          _permissionReady = await _checkPermission();
          if (_permissionReady) {
            await _prepareSaveDir();
            print("Downloading");
            try {
              await Dio().download("https://******/image.jpg",
                  _localPath   "/"   "filename.jpg");
              print("Download Completed.");
            } catch (e) {
              print("Download Failed.\n\n"   e.toString());
            }
          }
        },
        child: Container(
          decoration: BoxDecoration(
              shape: BoxShape.circle, color: Colors.grey.withOpacity(0.5)),
          padding: EdgeInsets.all(8),
          child: Icon(Icons.download, color: Colors.black),
        ));

Make sure you have added required permissions in the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  • Related