
作者:晚霞的不甘 日期:2025年12月14日 标签:Flutter · OpenHarmony · 软件架构 · 模块化 · 微前端 · 动态加载 · 鸿蒙生态 · 工程治理

你是否正面临这些困境?
main.dart,PR 冲突频发在 OpenHarmony 多设备、快迭代、强合规的背景下,单体架构已成技术负债。
本文提出一套面向鸿蒙生态的现代化 Flutter 应用架构体系,融合 模块化(Modularization)、微前端(Micro-Frontends)、动态能力(Dynamic Features)与分层治理(Layered Governance) 四大支柱,助你实现:
┌───────────────────────────────────────┐
│ 动态能力层 (Dynamic Layer) │ ← 按需加载,独立版本
│ ┌─────────────┐ ┌─────────────┐ │
│ │ 健康分析模块 │ │ 车机控制模块 │ ... │
│ └─────────────┘ └─────────────┘ │
├───────────────────────────────────────┤
│ 核心框架层 (Core Layer) │ ← 稳定、共享、受控
│ ┌───────────────────────────────┐ │
│ │ 路由中心 │ 状态管理 │ 安全服务 │ ... │
│ └───────────────────────────────┘ │
├───────────────────────────────────────┤
│ 基础设施层 (Infra Layer) │ ← 跨平台抽象
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Flutter SDK │ │ OH 插件桥接 │ ... │
│ └─────────────┘ └─────────────┘ │
└───────────────────────────────────────┘✅ 设计原则:
interface 通信,非直接调用health-superapp/
├── apps/
│ └── main_app/ # 主壳工程(轻量)
├── packages/
│ ├── core/ # 核心框架(路由、主题、i18n)
│ ├── features/
│ │ ├── health_monitor/ # 健康监测(独立模块)
│ │ ├── car_control/ # 车机控制(独立模块)
│ │ └── user_profile/ # 用户中心
│ └── shared/
│ ├── models/ # 共享数据模型
│ ├── utils/ # 通用工具
│ └── design_system/ # 组件库(适配多端)
├── plugins/
│ └── oh_health_sensor/ # 自研 OpenHarmony 插件
└── tools/
└── arch_lint/ # 架构约束检查脚本melos 管理)# melos.yaml
packages:
- apps/**
- packages/**
- plugins/**
dependency_overrides:
flutter: ^3.24.0
sdk: ">=3.4.0 <4.0.0"
scripts:
check-arch: |
dart run tools/arch_lint/bin/check.dart \
--forbid packages/features/*/ -> packages/features/*/🔒 强制约束:业务模块之间禁止直接依赖,必须通过
core或shared中转。
deferred loading 实现懒加载// core/lib/router/app_router.dart
import 'package:features/health_monitor/health_monitor_page.dart'
deferred as health;
class AppRouter {
Future<Widget> loadPage(String route) async {
switch (route) {
case '/health':
await health.loadLibrary(); // 动态加载
return health.HealthMonitorPage();
default:
throw Exception('Route not found');
}
}
}💡 HSP(Harmony Shared Package):OpenHarmony 支持的动态特性包,可独立更新。
// apps/main_app/module.json5
{
"dynamicFeatures": [
"health_analysis.hsp", // 健康分析引擎
"car_voice_control.hsp" // 车机语音控制
]
}health_analysis.hsp// shared/lib/interfaces/health_service.dart
abstract class IHealthService {
Stream<int> get heartRateStream;
Future<void> startMonitoring();
}
// features/health_monitor/lib/health_service_impl.dart
class HealthServiceImpl implements IHealthService { ... }
// core/lib/service_locator.dart
final locator = GetIt.instance;
locator.registerLazySingleton<IHealthService>(() => HealthServiceImpl());
// 其他模块使用
final service = locator<IHealthService>();
service.startMonitoring();✅ 优势:替换实现只需修改注册,调用方无感知。
// shared/design_system/lib/device_aware_widget.dart
Widget buildDeviceAware(BuildContext context, {
Widget? phone,
Widget? wearable,
Widget? car,
Widget? tv,
}) {
final device = OhDeviceType.current;
return switch (device) {
OhDeviceType.phone => phone ?? const SizedBox(),
OhDeviceType.wearable => wearable ?? const SizedBox(),
OhDeviceType.car => car ?? const SizedBox(),
OhDeviceType.tv => tv ?? const SizedBox(),
};
}// features/health_monitor/lib/monitor_presenter.dart
void startMonitoring() {
if (OhDevice.hasSensor(SensorType.heartRate)) {
_sensorService.start();
}
if (OhDevice.supports(DistributedCapability.taskMigration)) {
_distributedService.enableSync();
}
}📊 效果:手表端仅包含传感器逻辑,车机端仅包含显示逻辑,包体积减少 40%+。
# 使用 melos + build_runner
melos run build --scope=health_monitor --include-dependentshealth_monitor → 仅重新构建该模块及其依赖者# .gitlab-ci.yml
build_all_devices:
script:
- flutter build ohos --target-platform=ohos-arm64 --flavor phone
- flutter build ohos --target-platform=ohos-arm64 --flavor wearable
- flutter build ohos --target-platform=ohos-arm64 --flavor car
parallel:
matrix:
- DEVICE: [phone, wearable, car]publish_health_hsp:
only:
changes:
- packages/features/health_analysis/**
script:
- cd packages/features/health_analysis
- flutter build hsp --release
- agc-cli upload-hsp health_analysis.hsp// tools/arch_lint/bin/check.dart
void main() {
final graph = DependencyGraph.load('pubspec.lock');
// 规则1:features/ 之间不能互相依赖
for (var module in graph.modules.where((m) => m.isFeature)) {
assert(!module.dependencies.any((d) => d.isFeature),
'Feature modules must not depend on each other');
}
// 规则2:core/ 不能依赖 features/
assert(!graph.core.dependencies.any((d) => d.isFeature),
'Core must not depend on features');
}指标 | 目标值 | 监控方式 |
|---|---|---|
模块间循环依赖 | 0 | arch_lint 扫描 |
单模块最大 LoC | ≤ 5k | SonarQube |
核心层变更频率 | ≤ 1次/周 | Git 日志分析 |
动态模块加载成功率 | ≥ 99% | AppTouch 监控 |
core/ 和 shared/features/🔄 关键:每次 PR 必须通过
arch_lint,否则阻断合并。
优秀的架构应具备:
🧩 行动建议:
melos 初始化 Monorepocore 模块(如路由)因为最好的架构,是那个能让你明天更轻松的架构。
附录:推荐工具链
类别 | 工具 | 用途 |
|---|---|---|
Monorepo 管理 | Melos | 包依赖、脚本统一 |
架构分析 | CodeMR / SonarQube | 耦合度、圈复杂度 |
动态加载 | Flutter Deferred + HSP | 按需加载 |
依赖注入 | GetIt / Riverpod | 解耦模块通信 |
多端构建 | DevEco CLI | 并行生成多设备 HAP |
架构的终极目标,不是追求完美,而是让变化不再痛苦。