Flutter外部资源加载插件external_asset_bundle的使用

Flutter外部资源加载插件external_asset_bundle的使用

External Asset Bundle简介

External Asset Bundle 插件的工作方式与 rootBundleDefaultAssetBundle 类似,但它可以从应用程序或库路径等外部位置加载资源。它还实现了资源加载的缓存功能。

如果你希望从临时文件夹或外部存储中加载资源,这个插件非常有用。

你可以像默认的 AssetBundle 一样使用 Image.asset 来创建一个 Image 实例:

var externalAssetBundle = ExternalAssetBundle("download/folder/assets");
var image = Image.asset(
      "sample.png",
      bundle: externalAssetBundle,	// 别忘了使用你自己的 AssetBundle!
    );

或者可以轻松地从路径加载字符串文件:

var stringContent = externalAssetBundle.loadString("some-text-file.txt");

ExternalAssetBundle 实现了抽象类 AssetBundle,因此它可以用于任何需要 AssetBundle 的地方。

此外,你不需要在 pubspec.yaml 文件中预先定义文件夹结构。文件夹结构会动态获取。不过,你仍然需要遵循默认资产文件夹的构造规则。

了解更多:Flutter 资源和图片


安装

在你的 pubspec.yaml 文件中添加 external_asset_bundle 作为依赖项:

dependencies:
  external_asset_bundle: 1.0.0

然后运行以下命令安装依赖:

flutter pub get

使用方法

初始化

唯一需要做的就是创建一个 ExternalAssetBundle 实例:

import 'package:external_asset_bundle/external_asset_bundle.dart';

var externalAssetBundle = ExternalAssetBundle("path/to/any/folder");

使用示例

你可以像使用任何 AssetBundle 一样使用它:

var image = Image.asset(
      "sample.png",
      bundle: externalAssetBundle,
    );

var stringContent = externalAssetBundle.loadString("some-text-file.txt");

如果你管理的文件夹结构如下:

asset-folder/sample.png
asset-folder/2.0x/sample.png
asset-folder/3.0x/sample.png

Image.asset 可以正确找到对应的变体。

缓存

通过在初始化 ExternalAssetBundle 时启用 enableBinaryCache 参数,可以实现资源缓存:

var externalAssetBundle = ExternalAssetBundle("path", enableBinaryCache: true);

但是,loadString 会根据其自身的 cache 参数来决定是否使用缓存。


完整示例代码

以下是一个完整的示例代码,展示如何使用 external_asset_bundle 插件加载外部资源:

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

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late ExternalAssetBundle externalAssetBundle;
  String? stringContent;

  @override
  void initState() {
    super.initState();
    // 初始化 ExternalAssetBundle
    externalAssetBundle = ExternalAssetBundle("assets");

    // 异步加载字符串内容
    loadStringContent();
  }

  Future<void> loadStringContent() async {
    stringContent = await externalAssetBundle.loadString("example.txt");
    setState(() {}); // 更新 UI
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("External Asset Bundle 示例"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 加载图片
            Image.asset(
              "logo.png",
              bundle: externalAssetBundle,
              width: 100,
              height: 100,
            ),
            SizedBox(height: 20),
            // 显示文本内容
            Text(stringContent ?? "正在加载..."),
          ],
        ),
      ),
    );
  }
}

文件夹结构

确保你的文件夹结构如下:

assets/logo.png
assets/example.txt

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

1 回复

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


external_asset_bundle 是一个 Flutter 插件,它允许你从外部资源(如网络或本地文件系统)加载资产(assets),而不是将它们打包到应用程序的 APK 或 IPA 中。这对于需要动态加载资源或减少应用程序初始大小的场景非常有用。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 external_asset_bundle 插件:

dependencies:
  flutter:
    sdk: flutter
  external_asset_bundle: ^0.1.0  # 请使用最新版本

然后运行 flutter pub get 来安装插件。

使用插件

  1. 创建 ExternalAssetBundle 实例

    你可以通过指定一个包含资源的 ZIP 文件的 URL 或本地路径来创建一个 ExternalAssetBundle 实例。

    import 'package:external_asset_bundle/external_asset_bundle.dart';
    
    final assetBundle = ExternalAssetBundle.fromZipUrl(
      'https://example.com/path/to/your/assets.zip',
    );
    

    或者从本地文件系统加载:

    final assetBundle = ExternalAssetBundle.fromZipFile(
      '/path/to/your/assets.zip',
    );
    
  2. 加载资源

    你可以使用 loadStringloadBytesloadImage 方法来加载资源。

    // 加载字符串资源
    final String text = await assetBundle.loadString('assets/text.txt');
    
    // 加载二进制资源
    final Uint8List bytes = await assetBundle.loadBytes('assets/image.png');
    
    // 加载图片资源
    final Image image = await assetBundle.loadImage('assets/image.png');
    
  3. 在 UI 中使用加载的资源

    你可以在 Flutter 的 UI 中使用这些加载的资源,例如在 ImageText 组件中。

    Image.memory(bytes),  // 显示加载的图片
    Text(text),          // 显示加载的文本
    

完整示例

以下是一个完整的示例,展示如何使用 external_asset_bundle 从网络加载并显示一张图片:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('External Asset Bundle Example'),
        ),
        body: Center(
          child: FutureBuilder(
            future: _loadImage(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                return snapshot.data;
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }

  Future<Widget> _loadImage() async {
    final assetBundle = ExternalAssetBundle.fromZipUrl(
      'https://example.com/path/to/your/assets.zip',
    );
    final Uint8List bytes = await assetBundle.loadBytes('assets/image.png');
    return Image.memory(bytes);
  }
}

注意事项

  1. 网络权限: 如果你从网络加载资源,确保在 AndroidManifest.xml 中添加网络权限:

    <uses-permission android:name="android.permission.INTERNET" />
回到顶部