Flutter资源下载插件download_assets的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter资源下载插件download_assets的使用

download_assets 是一个强大的库,用于在应用程序中下载资源文件(如图片、视频等)。它提供了简单易用的接口来处理下载和解压缩的过程。

关于

download_assets 包可以帮助开发者轻松地将各种类型的文件下载到应用中,并提供了一系列方法来管理下载过程中的状态和进度。

功能

初始化

首先需要初始化 DownloadAssetsController,设置资产目录:

await downloadAssetsController.init();

开始下载

开始下载资源文件:

await downloadAssetsController.startDownload(
    onCancel: () {
        // 用户取消下载时的操作
    },
    assetsUrls: [
      'https://github.com/edjostenes/download_assets/raw/main/download/image_1.png',
      'https://github.com/edjostenes/download_assets/raw/main/download/assets.zip',
      'https://github.com/edjostenes/download_assets/raw/main/download/image_2.png',
      'https://github.com/edjostenes/download_assets/raw/main/download/image_3.png',
    ],
    onProgress: (progressValue) {
        // 下载进度更新
    },
    onDone: () {
      // 下载完成后的操作
    }
);

清除已下载的资源

可以调用以下方法清除本地存储的所有下载资源:

await downloadAssetsController.clearAssets();

获取资源目录路径

获取资源文件的存储路径:

File('${downloadAssetsController.assetsDir}/<file_name>.<file_extension>');

检查资源目录是否存在

检查资源目录是否已经存在:

return await downloadAssetsController.assetsDirAlreadyExists();

检查特定文件是否存在

检查某个文件是否已经下载:

return await downloadAssetsController.assetsFileExists(<file_name>);

解压委托

为了支持不同类型的压缩文件(如ZIP、RAR等),你可以实现自定义的解压委托:

abstract class UncompressDelegate {
  const UncompressDelegate();

  String get extension;

  Future uncompress(String compressedFilePath, String assetsDir);
}

示例代码

下面是一个完整的示例,展示了如何使用 download_assets 插件:

import 'dart:io';
import 'package:download_assets/download_assets.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Download Assets Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage(title: 'Download Assets'),
      );
}

class MyHomePage extends StatefulWidget {
  MyHomePage({required this.title});

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DownloadAssetsController downloadAssetsController = DownloadAssetsController();
  String message = 'Press the download button to start the download';
  bool downloaded = false;
  double value = 0.0;

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

  Future _init() async {
    await downloadAssetsController.init();
    downloaded = await downloadAssetsController.assetsDirAlreadyExists();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              if (downloaded) ...[
                Container(
                  width: 150,
                  height: 150,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: FileImage(File('${downloadAssetsController.assetsDir}/dart.jpeg')),
                      fit: BoxFit.fitWidth,
                    ),
                  ),
                ),
                Container(
                  width: 150,
                  height: 150,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: FileImage(File('${downloadAssetsController.assetsDir}/flutter.png')),
                      fit: BoxFit.fitWidth,
                    ),
                  ),
                ),
              ],
              TweenAnimationBuilder<double>(
                duration: const Duration(milliseconds: 250),
                curve: Curves.easeInOut,
                tween: Tween<double>(
                  begin: 0,
                  end: value,
                ),
                builder: (context, value, _) => LinearProgressIndicator(
                  minHeight: 10,
                  value: value,
                ),
              ),
              Text(
                message,
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
        floatingActionButton: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FloatingActionButton(
              onPressed: _downloadAssets,
              tooltip: 'Download',
              child: Icon(Icons.arrow_downward),
            ),
            const SizedBox(
              width: 25,
            ),
            FloatingActionButton(
              onPressed: () async {
                await downloadAssetsController.clearAssets();
                await _downloadAssets();
              },
              tooltip: 'Refresh',
              child: Icon(Icons.refresh),
            ),
            const SizedBox(
              width: 25,
            ),
            FloatingActionButton(
              onPressed: _cancel,
              tooltip: 'Cancel',
              child: Icon(Icons.cancel_outlined),
            ),
          ],
        ),
      );

  Future _downloadAssets() async {
    final assetsDownloaded = await downloadAssetsController.assetsDirAlreadyExists();

    if (assetsDownloaded) {
      setState(() {
        message = 'Click in refresh button to force download';
        print(message);
      });
      return;
    }

    try {
      value = 0.0;
      downloaded = false;
      await downloadAssetsController.startDownload(
          onCancel: () {
            message = 'Cancelled by user';
            setState(() {});
          },
          assetsUrls: [
            'https://github.com/edjostenes/download_assets/raw/main/download/image_1.png',
            'https://github.com/edjostenes/download_assets/raw/main/download/assets.zip',
            'https://github.com/edjostenes/download_assets/raw/main/download/image_2.png',
            'https://github.com/edjostenes/download_assets/raw/main/download/image_3.png',
          ],
          onProgress: (progressValue) {
            value = progressValue;
            setState(() {
              message = 'Downloading - ${(progressValue * 100).toStringAsFixed(2)}';
              print(message);
            });
          },
          onDone: () {
            setState(() {
              downloaded = true;
              message = 'Download completed\nClick in refresh button to force download';
            });
          });
    } on DownloadAssetsException catch (e) {
      print(e.toString());
      setState(() {
        downloaded = false;
        message = 'Error: ${e.toString()}';
      });
    }
  }

  void _cancel() => downloadAssetsController.cancelDownload();
}

以上代码展示了如何在Flutter应用中使用 download_assets 插件进行资源下载和管理。希望这个示例能帮助你更好地理解和使用该插件。


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

1 回复

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


当然,以下是如何在Flutter项目中使用download_assets插件来下载资源的示例代码。这个插件允许你在运行时从远程服务器下载文件并将其保存到设备的存储中。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  download_assets: ^x.y.z  # 替换为最新版本号

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

2. 导入插件

在你需要使用下载功能的Dart文件中导入download_assets插件:

import 'package:download_assets/download_assets.dart';

3. 配置权限

在Android上,你可能需要在AndroidManifest.xml中添加存储权限:

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

对于iOS,确保你的Info.plist文件包含必要的权限配置,如NSAppTransportSecurity以允许HTTP请求。

4. 下载资源

以下是一个简单的示例,演示如何使用download_assets插件下载文件:

import 'package:flutter/material.dart';
import 'package:download_assets/download_assets.dart';
import 'package:path_provider/path_provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DownloadScreen(),
    );
  }
}

class DownloadScreen extends StatefulWidget {
  @override
  _DownloadScreenState createState() => _DownloadScreenState();
}

class _DownloadScreenState extends State<DownloadScreen> {
  String downloadStatus = "";

  void downloadFile() async {
    // 获取应用文档目录的路径
    final directory = await getApplicationDocumentsDirectory();
    final localPath = directory.path;

    // 定义下载文件的URL和保存路径
    final url = "https://example.com/path/to/your/file.zip";
    final fileName = "file.zip";
    final filePath = "$localPath/$fileName";

    // 调用下载函数
    try {
      await DownloadAssets.downloadFile(
        url: url,
        destination: filePath,
        onProgress: (progress) {
          // 更新UI或显示下载进度
          setState(() {
            downloadStatus = "${(progress.receivedBytes / progress.totalBytes * 100).toInt()}%";
          });
        },
      );

      // 下载完成后显示成功信息
      setState(() {
        downloadStatus = "Download completed!";
      });
    } catch (e) {
      // 处理下载错误
      setState(() {
        downloadStatus = "Download failed: ${e.message}";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Download File Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(downloadStatus),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: downloadFile,
              child: Text("Download File"),
            ),
          ],
        ),
      ),
    );
  }
}

5. 运行应用

完成上述步骤后,你可以使用flutter run命令来运行你的Flutter应用。点击按钮后,它将尝试从指定的URL下载文件,并在UI上显示下载进度或结果。

请确保将示例中的URL替换为你实际的文件URL,并根据需要调整文件名和路径。这个示例展示了基本的下载功能,你可以根据需求进一步扩展,比如处理不同类型的文件、下载多个文件、管理下载队列等。

回到顶部