flutter_downloader 1.3.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 99

Flutter Community: flutter_downloader

Flutter Downloader #

pub package

A plugin for creating and managing download tasks. Supports iOS and Android.

This plugin is based on WorkManager in Android and NSURLSessionDownloadTask in iOS to run download task in background mode.

iOS integration #

Required configuration: #

Note: following steps requires to open your ios project in Xcode.

  • Enable background mode.
  • Add sqlite library.

  • Configure AppDelegate:

Objective-C:

/// AppDelegate.h
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>

@interface AppDelegate : FlutterAppDelegate

@end
// AppDelegate.m
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#include "FlutterDownloaderPlugin.h"

@implementation AppDelegate

void registerPlugins(NSObject<FlutterPluginRegistry>* registry) {
  [GeneratedPluginRegistrant registerWithRegistry:registry];
}

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  [FlutterDownloaderPlugin setPluginRegistrantCallback:registerPlugins];
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

Or Swift:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

private func registerPlugins(registry: FlutterPluginRegistry) {
    GeneratedPluginRegistrant.register(with: registry)
}

Optional configuration: #

  • Support HTTP request: if you want to download file with HTTP request, you need to disable Apple Transport Security (ATS) feature. There're two options:
  1. Disable ATS for a specific domain only: (add following codes to your Info.plist file)
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>www.yourserver.com</key>
    <dict>
      <!-- add this key to enable subdomains such as sub.yourserver.com -->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!-- add this key to allow standard HTTP requests, thus negating the ATS -->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!-- add this key to specify the minimum TLS version to accept -->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>
  1. Completely disable ATS: (add following codes to your Info.plist file)
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key><true/>
</dict>
  • Configure maximum number of concurrent tasks: the plugin allows 3 download tasks running at a moment by default (if you enqueue more than 3 tasks, there're only 3 tasks running, other tasks are put in pending state). You can change this number by adding following codes to your Info.plist file.
<!-- changes this number to configure the maximum number of concurrent tasks -->
<key>FDMaximumConcurrentTasks</key>
<integer>5</integer>
  • Localize notification messages: the plugin will send a notification message to notify user in case all files are downloaded while your application is not running in foreground. This message is English by default. You can localize this message by adding and localizing following message in Info.plist file. (you can find the detail of Info.plist localization in this link)
<key>FDAllFilesDownloadedMessage</key>
<string>All files have been downloaded</string>

Note:

  • This plugin only supports save files in NSDocumentDirectory

Android integration #

Required configuration: #

  • Configure Application:

Java:

// MyApplication.java
public class MyApplication extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void registerWith(PluginRegistry registry) {
        GeneratedPluginRegistrant.registerWith(registry);
    }
}

Or Kotlin:

// MyApplication.kt
internal class MyApplication : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun registerWith(registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry)
    }
}

And update AndroidManifest.xml

<!-- AndroidManifest.xml -->
<application
        android:name=".MyApplication"
        ....>
  • In order to handle click action on notification to open the downloaded file on Android, you need to add some additional configurations. Add the following codes to your AndroidManifest.xml:
<provider
    android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
    android:authorities="${applicationId}.flutter_downloader.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

Note:

  • You have to save your downloaded files in external storage (where the other applications have permission to read your files)
  • The downloaded files are only able to be opened if your device has at least an application that can read these file types (mp3, pdf, etc)

Optional configuration: #

  • Configure maximum number of concurrent tasks: the plugin depends on WorkManager library and WorkManager depends on the number of available processor to configure the maximum number of tasks running at a moment. You can setup a fixed number for this configuration by adding following codes to your AndroidManifest.xml:
 <provider
     android:name="androidx.work.impl.WorkManagerInitializer"
     android:authorities="${applicationId}.workmanager-init"
     android:enabled="false"
     android:exported="false" />

 <provider
     android:name="vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"
     android:authorities="${applicationId}.flutter-downloader-init"
     android:exported="false">
     <!-- changes this number to configure the maximum number of concurrent tasks -->
     <meta-data
         android:name="vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS"
         android:value="5" />
 </provider>
  • Localize notification messages: you can localize notification messages of download progress by localizing following messages. (you can find the detail of string localization in Android in this link)
<string name="flutter_downloader_notification_started">Download started</string>
<string name="flutter_downloader_notification_in_progress">Download in progress</string>
<string name="flutter_downloader_notification_canceled">Download canceled</string>
<string name="flutter_downloader_notification_failed">Download failed</string>
<string name="flutter_downloader_notification_complete">Download complete</string>
<string name="flutter_downloader_notification_paused">Download paused</string>
  • PackageInstaller: in order to open APK files, your application needs REQUEST_INSTALL_PACKAGES permission. Add following codes in your AndroidManifest.xml:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

Usage #

Import package: #

import 'package:flutter_downloader/flutter_downloader.dart';

Initialize #

await FlutterDownloader.initialize();
  • Note: the plugin must be initialized before using.

Create new download task: #

final taskId = await FlutterDownloader.enqueue(
  url: 'your download link',
  savedDir: 'the path of directory where you want to save downloaded files',
  showNotification: true, // show download progress in status bar (for Android)
  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);

Update download progress: #

FlutterDownloader.registerCallback(callback); // callback is a top-level or static function

Important note: your UI is rendered in the main isolate, while download events come from a background isolate (in other words, codes in callback are run in the background isolate), so you have to handle the communication between two isolates. For example:

ReceivePort _port = ReceivePort();

@override
void initState() {
	super.initState();

	IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
	_port.listen((dynamic data) {
		String id = data[0];
		DownloadTaskStatus status = data[1];
		int progress = data[2];
		setState((){ });
	});

	FlutterDownloader.registerCallback(downloadCallback);
}

static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
	final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
	send.send([id, status, progress]);
}

Load all tasks: #

final tasks = await FlutterDownloader.loadTasks();

Load tasks with conditions: #

final tasks = await FlutterDownloader.loadTasksWithRawQuery(query: query);
  • Note: In order to parse data into DownloadTask object successfully, you should load data with all fields from DB (in the other word, use: SELECT * ). For example:
SELECT * FROM task WHERE status=3
  • Note: the following is the schema of task table where this plugin stores tasks information
CREATE TABLE `task` (
	`id`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`task_id`	VARCHAR ( 256 ),
	`url`	TEXT,
	`status`	INTEGER DEFAULT 0,
	`progress`	INTEGER DEFAULT 0,
	`file_name`	TEXT,
	`saved_dir`	TEXT,
	`resumable`	TINYINT DEFAULT 0,
	`headers`	TEXT,
	`show_notification`	TINYINT DEFAULT 0,
	`open_file_from_notification`	TINYINT DEFAULT 0,
	`time_created`	INTEGER DEFAULT 0
);

Cancel a task: #

FlutterDownloader.cancel(taskId: taskId);

Cancel all tasks: #

FlutterDownloader.cancelAll();

Pause a task: #

FlutterDownloader.pause(taskId: taskId);

Resume a task: #

FlutterDownloader.resume(taskId: taskId);
  • Note: resume() will return a new taskId corresponding to a new background task that is created to continue the download process. You should replace the original taskId (that is marked as paused status) by this new taskId to continue tracking the download progress.

Retry a failed task: #

FlutterDownloader.retry(taskId: taskId);
  • Note: retry() will return a new taskId (like resume())

Remove a task: #

FlutterDownloader.remove(taskId: taskId, shouldDeleteContent:false);

Open and preview a downloaded file: #

FlutterDownloader.open(taskId: taskId);
  • Note: in Android, you can only open a downloaded file if it is placed in the external storage and there's at least one application that can read that file type on your device.

Bugs/Requests #

If you encounter any problems feel free to open an issue. If you feel the library is missing a feature, please raise a ticket on Github. Pull request are also welcome.

1.3.1 - 18.09.2019 #

  • assert the initialization of FlutterDownloader

1.3.0 - 16.09.2019 #

  • BREAKING CHANGES: the plugin has been refactored to support update download events with background isolate. In order to support background execution in Dart, the callback, that receives events from platform codes, now must be a static or top-level function. There's also an additional native configuration required on both of iOS and Android. See README for detail.
  • Android: upgrade WorkManager to v2.2.0.
  • Fix bug SecurityException when saving image/videos to internal storage in Android
  • Fix bug cannot save videos in Android.

1.2.2 - 19.09.2019 #

  • Android: fix bugs

1.2.1 - 27.08.2019 #

  • Android: hot-fix unregister BroadcastReceiver in case using FlutterFragmentActivity

1.2.0 - 27.08.2019 #

  • Android: support FlutterFragmentActivity, fix bug downloaded image/video files not shown in Gallery application, improved HTTP redirection implementation, fix bug cannot open apk file in some cases

1.1.9 - 18.07.2019 #

  • Android: support HTTP redirection
  • iOS: correct getting file name from HTTP response

1.1.8 - 16.07.2019 #

  • Fix bug in iOS: from iOS 8, absolute path to app's sandbox changes every time you relaunch the app, hence savedDir path is needed to truncate the changing part before saving it to DB and recreate the absolute path every time it loaded from DB. Currently, the plugin only supports save files in NSDocumentDirectory.
  • Fix bug is iOS: setting wrong status of task in case that the application is terminated
  • Android: upgrade dependencies

1.1.7 - 24.03.2019 #

  • Android: upgrade WorkManager to version 2.0.0 (AndroidX)

1.1.6 - 09.02.2019 #

  • Android: upgrade WorkManager to version 1.0.0-beta05
  • Android: migrate to AndroidX

1.1.5 - 27.01.2019 #

  • Android: upgrade WorkManager to version 1.0.0-beta03
  • fix bugs

1.1.4 - 06.01.2019 #

  • add remove() feature to delete task (in DB) and downloaded file as well (optional).
  • support clean up callback by setting callback as null in registerCallback()
  • Android: upgrade WorkManager to version 1.0.0-beta01

1.1.3 - 18.11.2018 #

  • Android: fix bug NullPointerException of saveFilePath

1.1.2 - 14.11.2018 #

  • Android: fix typo error
  • iOS: catch HTTP status code in case of error

1.1.1 - 12.11.2018 #

  • correct README instruction

1.1.0 - 12.11.2018 #

  • Android: upgrade WorkManager library to version v1.0.0-alpha11
  • BREAKING CHANGE: initialize() is removed (to deal with the change of the initialization of WorkManager in v1.0.0-alpha11). The plugin initializes itself with default configurations. If you would like to change the default configuration, you can follows the instruction in README.md

1.0.6 - 28.10.2018 #

  • fix bug related to filename

1.0.5 - 22.10.2018 #

  • Android: re-config dependencies

1.0.4 - 20.10.2018 #

  • Android: upgrade WorkManager to v1.0.0-alpha10

1.0.3 - 29.09.2018 #

  • Android: upgrade compile sdk version to 28

1.0.2 - 20.09.2018 #

  • Fixed Flutter Community badge.

1.0.1 - 20.09.2018 #

1.0.0 - 09.09.2018 #

  • NEW features: initialize, loadTasksWithRawQuery, pause, resume, retry, open
  • IMPORTANT: the plugin must be initialized by initialize() at first
  • BREAKING CHANGE: clickToOpenDownloadedFile now renames to openFileFromNotification (to prevent confusing from open feature). Static property maximumConcurrentTask has been removed, this configuration now moves into initialize() method.
  • full support SQLite on both Android and iOS side, the plugin now itself manages its states persistently and exposes loadTasksWithRawQuery api that helps developers to load tasks from SQLite database with customized conditions
  • support localizing Android notification messages with messages parameter of initialize() method
  • full support opening and previewing downloaded file with open() method
  • (iOS integration) no need to override application:handleEventsForBackgroundURLSession:completionHandler: manually anymore, the plugin now itself takes responsibility for handling it

0.1.1 - 29.08.2018 #

  • fix bugs: SQLite leak
  • new feature: support configuration of the maximum of concurrent download tasks
  • upgrade WorkManager to v1.0.0-alpha08

0.1.0 - 12.08.2018 #

  • add: handle click on notification to open downloaded file (for Android)

0.0.9 - 10.08.2018 #

  • re-config to support Dart2

0.0.8 - 10.08.2018 #

  • upgrade WorkManager to v1.0.0-alpha06
  • fix bug: disable sound on notifications

0.0.7 - 28.06.2018 #

  • upgrade WorkManager to v1.0.0-alpha04

0.0.6 - 28.06.2018 #

  • upgrade WorkManager to v1.0.0-alpha03
  • change default value of showNotification to true (it makes sense on Android 8.0 and above, it helps our tasks not to be killed by system when the app goes to background)

0.0.5 - 22.06.2018 #

  • update metadata

0.0.4 - 15.06.2018 #

  • fix bug: Worker finished with FAILURE on Android API 26 and above

0.0.3 - 11.06.2018 #

  • support HTTP headers

0.0.2 - 08.06.2018 #

  • correct README document

0.0.1 - 07.06.2018 #

  • initial release.

example/README.md

flutter_downloader_example #

Demonstrates how to use the flutter_downloader plugin.

Getting Started #

For help getting started with Flutter, view our online documentation.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_downloader: ^1.3.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_downloader/flutter_downloader.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
97
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
99
Learn more about scoring.

We analyzed this package on Oct 18, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/flutter_downloader.dart.

Run flutter format to format lib/flutter_downloader.dart.

Format lib/src/downloader.dart.

Run flutter format to format lib/src/downloader.dart.

Format lib/src/models.dart.

Run flutter format to format lib/src/models.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.20.1 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test