Flutter文件下载插件fl_download的使用

Flutter文件下载插件fl_download的使用

开始使用

fl_download 是一个基于Dio实现的Flutter插件,用于文件下载。它简单、方便且快速,开箱即用,适用于Android、iOS等平台。

使用方法

示例代码

import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fl_download/download/down_file.dart';
import 'package:fl_download/fl_download.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _flDownloadPlugin = FlDownload();

  // 获取app临时文件路径
  Future<String> getFilePath(String type) async {
    var filepath = await getApplicationDocumentsDirectory(); // App内部file:data.com.nufang.zao/file/
    var file = Directory('${filepath.path}/$type');
    try {
      bool exists = await file.exists();
      if (!exists) {
        await file.create();
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
    return file.path;
  }

  @override
  void initState() {
    super.initState();
    initPlatformState();
    downloadDemo();
  }

  downloadDemo() async {
    String filePath = await getFilePath('download');
    String tempFilePath = '$filePath/${12345678}.mp3';
    
    // 下载音频文件
    DownFile().downInfo(
      'https://downsc.chinaz.net/files/download/sound1/201305/3055.mp3', // 文件URL
      tempFilePath, // 保存路径
      () async {
        if (kDebugMode) {
          print(("下载完成"));
        }
      },
    );

    // 下载视频文件到相册
    DownFile().downVideoToDCIM(
      "music_audio", // 目录名
      'https://music-aigc-bj-1256122840.cos.ap-beijing.myqcloud.com/bjprod/ai/youtube/5nmtCPO1NFY.m4a', // 文件URL
      () {
        if (kDebugMode) {
          print("下载成功");
        }
      },
    );
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flDownloadPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Text('运行在: $_platformVersion\n'),
        ),
      ),
    );
  }
}

说明

  1. 获取文件路径

    Future<String> getFilePath(String type) async {
      var filepath = await getApplicationDocumentsDirectory(); // 获取应用程序文档目录
      var file = Directory('${filepath.path}/$type'); // 创建指定类型的文件夹
      try {
        bool exists = await file.exists();
        if (!exists) {
          await file.create(); // 如果文件夹不存在,则创建
        }
      } catch (e) {
        if (kDebugMode) {
          print(e); // 打印错误信息
        }
      }
      return file.path; // 返回文件夹路径
    }
    
  2. 下载文件

    DownFile().downInfo(
      'https://downsc.chinaz.net/files/download/sound1/201305/3055.mp3', // 文件URL
      tempFilePath, // 保存路径
      () async {
        if (kDebugMode) {
          print(("下载完成")); // 打印下载完成信息
        }
      },
    );
    
  3. 下载视频文件到相册

    DownFile().downVideoToDCIM(
      "music_audio", // 目录名
      'https://music-aigc-bj-1256122840.cos.ap-beijing.myqcloud.com/bjprod/ai/youtube/5nmtCPO1NFY.m4a', // 文件URL
      () {
        if (kDebugMode) {
          print("下载成功"); // 打印下载成功信息
        }
      },
    );
    

更多关于Flutter文件下载插件fl_download的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文件下载插件fl_download的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


fl_download 是一个用于在 Flutter 应用中下载文件的插件。它可以帮助你轻松地处理文件下载任务,并提供下载进度、暂停、恢复、取消等功能的支持。以下是如何在 Flutter 项目中使用 fl_download 插件的简要指南。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 fl_download 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  fl_download: ^1.0.0  # 请确保使用最新的版本号

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在你的 Dart 代码中,首先需要导入 fl_download 插件:

import 'package:fl_download/fl_download.dart';

然后,在应用的入口点(如 main 函数)中初始化插件:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FLDownload.initialize();
  runApp(MyApp());
}

3. 下载文件

你可以使用 FLDownload.download 方法来下载文件。此方法接受一个 url 和一个 savePath 作为参数:

void downloadFile() async {
  String url = 'https://example.com/file.zip';  // 文件的 URL
  String savePath = '/storage/emulated/0/Download/file.zip';  // 文件的保存路径

  try {
    final taskId = await FLDownload.download(url, savePath);
    print('Download started with taskId: $taskId');
  } catch (e) {
    print('Failed to start download: $e');
  }
}

4. 监听下载进度

你可以使用 FLDownload.onProgress 流来监听下载进度:

void listenToDownloadProgress() {
  FLDownload.onProgress.listen((progress) {
    print('Download progress: ${progress.progress}%');
    print('Downloaded bytes: ${progress.downloadedBytes}');
    print('Total bytes: ${progress.totalBytes}');
  });
}

5. 暂停、恢复和取消下载

你可以使用 FLDownload.pauseFLDownload.resumeFLDownload.cancel 方法来控制下载任务:

void pauseDownload(String taskId) async {
  await FLDownload.pause(taskId);
}

void resumeDownload(String taskId) async {
  await FLDownload.resume(taskId);
}

void cancelDownload(String taskId) async {
  await FLDownload.cancel(taskId);
}

6. 检查下载状态

你可以使用 FLDownload.status 方法来检查下载任务的状态:

void checkDownloadStatus(String taskId) async {
  final status = await FLDownload.status(taskId);
  print('Download status: $status');
}

7. 处理下载完成事件

你可以使用 FLDownload.onComplete 流来监听下载完成的事件:

void listenToDownloadComplete() {
  FLDownload.onComplete.listen((taskId) {
    print('Download completed with taskId: $taskId');
  });
}

8. 处理下载失败事件

你可以使用 FLDownload.onError 流来监听下载失败的事件:

void listenToDownloadError() {
  FLDownload.onError.listen((error) {
    print('Download error: $error');
  });
}

9. 示例代码

以下是一个简单的完整示例,展示了如何使用 fl_download 插件下载文件并监听进度和完成事件:

import 'package:flutter/material.dart';
import 'package:fl_download/fl_download.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FLDownload.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Download Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              downloadFile();
              listenToDownloadProgress();
              listenToDownloadComplete();
              listenToDownloadError();
            },
            child: Text('Download File'),
          ),
        ),
      ),
    );
  }

  void downloadFile() async {
    String url = 'https://example.com/file.zip';
    String savePath = '/storage/emulated/0/Download/file.zip';

    try {
      final taskId = await FLDownload.download(url, savePath);
      print('Download started with taskId: $taskId');
    } catch (e) {
      print('Failed to start download: $e');
    }
  }

  void listenToDownloadProgress() {
    FLDownload.onProgress.listen((progress) {
      print('Download progress: ${progress.progress}%');
      print('Downloaded bytes: ${progress.downloadedBytes}');
      print('Total bytes: ${progress.totalBytes}');
    });
  }

  void listenToDownloadComplete() {
    FLDownload.onComplete.listen((taskId) {
      print('Download completed with taskId: $taskId');
    });
  }

  void listenToDownloadError() {
    FLDownload.onError.listen((error) {
      print('Download error: $error');
    });
  }
}
回到顶部