패키지, 저장소 및 앱 카테고리 검색

패키지 상세v9.6.5

background_downloader

다중 플랫폼 백그라운드 파일 다운로더 및 업로더입니다. 작업을 정의하고 대기열에 넣고 진행 상황을 모니터링합니다

AndroidiOSmacOSWindowsLinux
30일 다운로드
27.7만
좋아요
505
Pub 점수
160

패키지 설치

flutter pub add background_downloader

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Android, iOS, macOS, Windows, Linux에서 백그라운드 파일 다운로드 및 업로드를 가능하게 하는 크로스 플랫폼 플러터 패키지입니다. 개발자는 다운로드/업로드 작업을 정의하고 실행을 위해 대기열에 넣으며 실시간으로 진행 상황을 모니터링할 수 있습니다. 신뢰성과 효율성을 고려하여 설계되었으며, 네트워크 차단 시에도 작업을 계속하고 앱 재시작 후에도 이어갑니다. UI를 차단하지 않고 대용량 파일 전송이 필요한 앱에 적합합니다.

사용 사례

  • 큰 미디어 파일 다운로드
  • 사용자 생성 콘텐츠 업로드
  • 오프라인 데이터 동기화
  • 백그라운드 파일 업데이트
  • 지속 가능한 작업 관리

주요 기능

  • 크로스 플랫폼 지원
  • 실시간 진행 상황 모니터링
  • 재시작 간 작업 지속성
  • 재개 가능한 다운로드/업로드
  • 작업 정의를 위한 간단한 API

적합한 대상

  • 백그라운드 파일 전송이 필요한 앱
  • 미디어 또는 문서 중심 애플리케이션
  • 오프라인 우선 모바일 앱
  • 큰 자산 번들 포함 애플리케이션

고려 사항

  • 적절한 플랫폼 전용 권한이 필요합니다
  • iOS에서 백그라운드 실행을 위해 추가 구성이 필요할 수 있습니다
  • 네트워크 상태는 성능에 영향을 미칩니다
  • 큰 파일은 신중한 메모리 관리가 필요합니다
  • 일부 플랫폼의 백그라운드 실행 제한

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

A background file downloader and uploader for iOS, Android, MacOS, Windows and Linux

A robust, multi-platform background file transfer plugin for Flutter supporting background downloads, uploads, and data tasks across iOS, Android, MacOS, Windows, and Linux.

Uses native URLSession on iOS and MacOS, and DownloadWorker (WorkManager) / JobService (UIDT) on Android, ensuring transfers continue even when your app is in the background or terminated by the OS.


🌟 The Modern Transfer API (Recommended)

The easiest and most powerful way to use background_downloader is via the Transfer API.

On app startup (e.g. in main() or your top-level initState()), call FileDownloader().start(autoCleanDatabase: true) to activate persistent database tracking, automatically purge old task records, and reconcile transfers that completed or were interrupted while the app was suspended or closed. Then simply define a DownloadTask or UploadTask, start it using FileDownloader().transfers.start, and receive a reactive Transfer handle:

// 1. Activate database tracking & auto-cleanup on app launch (recommended)
await FileDownloader().start(autoCleanDatabase: true);

// 2. Configure notifications (recommended for userInitiated / UIDT tasks)
FileDownloader().configureNotification(
  running: const TaskNotification('Downloading', '{filename}'),
  complete: const TaskNotification('Complete', '{filename}'),
  progressBar: true,
  tapOpensFile: true,
);

// 3. Define the task with smart hints
final task = DownloadTask(
  url: 'https://example.com/large_video.mp4',
  filename: 'video.mp4',
  transferHints: {TransferHint.userInitiated, TransferHint.largeFile},
);

// 4. Start the transfer
final transfer = await FileDownloader().transfers.start(task);

// 5. Directly await the completed File:
final file = await transfer.file;
print('Downloaded to: ${file.path}');
Why use Transfer?
  • Awaitable Futures: Await transfer.file for the completed File, transfer.result for the TaskStatusUpdate, or transfer.responseBody for server response text.
  • Reactive UI Notifiers: Direct ValueNotifier bindings for Flutter widgets: transfer.progressNotifier (clean 0.0–1.0), transfer.statusNotifier, transfer.networkSpeedNotifier, transfer.timeRemainingNotifier, and transfer.notificationTapNotifier.
  • Plug-and-Play Widgets: Pre-built UI components including TransferProgressBar, TransferButton, and TransferListTile.
  • Direct Controls: Pause, resume, cancel, or allow cellular without managing task IDs: await transfer.pause(), await transfer.resume(), await transfer.cancel().
  • Batch Processing: Enqueue hundreds of transfers with aggregate progress using FileDownloader().transfers.startAll(tasks, onProgress: ...).
  • Smart Auto-Tuning & Android 14+ UIDT: Use TransferHint (userInitiated, largeFile, smallFile, lowPriority, useSuggestedFilename, binaryUpload) to configure optimal priority, Android 14+ UIDT, and pause resilience automatically.
  • Notification Tap Integration: React directly to user notification taps per transfer via transfer.notificationTapNotifier or open downloaded files automatically with tapOpensFile: true.
  • Scoping & Isolation: Modularize downloads in plugins or sub-features with isolated namespaces using FileDownloader.scoped('my_feature').
  • Network Resilience: Automatic offline holding and resume, plus configurable stall detection (stallTimeout).

👉 Read the complete Transfers Guide


🛠️ Lower-Level APIs

For specialized workflows or legacy integration, FileDownloader continues to provide direct lower-level methods:

Direct Awaitable Download (download)

Execute a task and wait for completion in a single call with inline callbacks:

final result = await FileDownloader().download(
  task,
  onProgress: (progress) => print('Progress: ${progress * 100}%'),
  onStatus: (status) => print('Status: $status'),
);

if (result.status == TaskStatus.complete) {
  print('Download finished!');
}
Queue & Event Streams (enqueue / enqueueAll)

For pipeline architectures where you monitor tasks centrally via a global stream or callbacks:

// 1. Listen centrally to task updates (typically in initState)
FileDownloader().updates.listen((update) {
  switch (update) {
    case TaskStatusUpdate():
      print('Task ${update.task.taskId} status: ${update.status}');
    case TaskProgressUpdate():
      print('Task ${update.task.taskId} progress: ${update.progress * 100}%');
  }
});

// 2. Start the downloader and activate persistent database tracking
FileDownloader().start();

// 3. Enqueue background tasks
final enqueued = await FileDownloader().enqueue(task);

📁 File Locations

To ensure file paths work robustly across platform restarts (especially on iOS and Android where container paths can change between app launches), the downloader uses a combination of BaseDirectory, directory (subdirectory) and filename:

  • BaseDirectory: One of .applicationDocuments, .temporary, .applicationSupport, or .applicationLibrary.
  • directory: An optional subdirectory within the base directory.
  • filename: The name of the file (or DownloadTask.suggestedFilename / '?' to use the server's Content-Disposition header).

See File Storage for details on shared and scoped storage.


📚 Documentation Index

Check the Topic Index or specific guides:


⚙️ Initial Setup

No setup is required for Windows or Linux.

Android

Requires Kotlin 2.1.0 or above. For modern Flutter projects, ensure your android/settings.gradle has:

plugins {
    id "org.jetbrains.kotlin.android" version "2.1.0" apply false
}
iOS

No special setup is required. By default iOS requires HTTPS connections (see Apple ATS Configuration if HTTP is required).

MacOS

Add the client network entitlement to macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements:

<key>com.apple.security.network.client</key>
<true/>

⚠️ Platform Notes & Limitations

  • iOS: Minimum iOS 14.0. Background transfers must complete within the system resource timeout (defaults to 4 hours, configurable via CONFIG.md).
  • Android: Minimum API 21. Standard background tasks are limited to 9 minutes by WorkManager. To allow longer downloads, set allowPause: true (or TransferHint.largeFile / userInitiated), which automatically resumes across 9-minute cycles, or set priority: 0 on Android 14+ to use UIDT (see parameters.md).
  • OS Termination: If the user forcefully swipes the app away from the iOS App Switcher or Android Recents, the OS may terminate background transfers without notification.

카테고리

의존성

의존성 목록 8 개

소스 저장소

이 패키지를 사용하는 프로젝트