【译】 Flutter 延迟加载组件 【包体积优化 _ 动态化】

本文介绍了如何在Flutter应用中使用SplitCompat和DeferredComponents进行模块化加载,包括在attachBaseContext中安装SplitCompat,声明SplitCompatApplication,处理延迟组件的安装,以及如何编写和使用延迟加载的Dart库,如DeferredBox。指南还涵盖了构建过程和验证步骤,以确保组件的正确加载和配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


}

  • 在 `attachBaseContext()` 中调用 `SplitCompat.install(this);`:

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// Emulates installation of future on demand modules using SplitCompat.
SplitCompat.install(this);
}

  • 将 `SplitCompatApplication` 声明为 application 的子类, 并将 `FlutterApplication` 中的 flutter 兼容性代码添加到你的 application 类中:

<application

android:name=“com.google.android.play.core.splitcompat.SplitCompatApplication”>

嵌入层依赖注入的 DeferredComponentManager 实例来处理延迟组件的安装请求。 通过在应用程序的初始流程中添加以下代码,将 PlayStoreDeferredComponentManager 添加到 Flutter 嵌入层中:

import io.flutter.embedding.engine.dynamicfeatures.PlayStoreDeferredComponentManager;
import io.flutter.FlutterInjector;

layStoreDeferredComponentManager deferredComponentManager = new
PlayStoreDeferredComponentManager(this, null);
FlutterInjector.setInstance(new FlutterInjector.Builder()
.setDeferredComponentManager(deferredComponentManager).build());

  1. 通过将 `deferred-components` 依赖添加到应用程序的 `pubspec.yaml` 中的 `flutter` 下,并选择延迟组件:


flutter:

deferred-components:

flutter 工具会在 pubspec.yaml 中查找 deferred-components, 来确定是否应将应用程序构建为延迟加载。 除非你已经知道所需的组件和每个组件中的 Dart 延迟库,否则可以暂时将其留空。 当 gen_snapshot 生成加载单元后,你可以在后面的 步骤 3.3 中完善这部分内容。

步骤 2:实现延迟加载的 Dart 库

接下来,在 Dart 代码中实现延迟加载的 Dart 库。实现并非立刻需要的功能。 文章剩余部分中的示例添加了一个简单的延迟 widget 作为占位。 你还可以通过修改 loadLibrary()Futures 后面的延迟加载代码的导入和保护用法,将现有代码转换为延迟代码。

  1. 创建新的 Dart 库。例如,创建一个可以在运行时下载的 `DeferredBox` widget。 这个 widget 可以是任意复杂的,本指南使用以下内容创建了一个简单的框。

// box.dart

import ‘package:flutter/widg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值