Flutter 插件开发实战:
用 amps_sdk 讲透 Android / iOS / HarmonyOS 广告桥接
摘要
Flutter 插件的本质,是在 Dart 和原生之间搭一座「消息桥」。广告 SDK 插件比普通插件更复杂:要处理异步回调、多广告位并行、全屏展示与信息流嵌入两种形态,还要在 Android、iOS、HarmonyOS 三端保持协议一致。
本文以公司开源广告Flutter插件项目 amps_sdk(AMPS 广告网络 Flutter 插件)为完整案例,从 MethodChannel 原理出发,讲清楚 Dart 层怎么设计 API、Native 层怎么解耦、多实例怎么隔离、自渲染怎么闭环。读完后,你应该能独立设计一套可上线的广告插件架构。
一、Flutter 插件在做什么
Flutter 应用运行在 Dart VM 里,原生 SDK(Java/Kotlin、Swift、ArkTS)跑在各自平台。两者不能直接互调,靠 Platform Channel 传消息:
┌─────────────────┐ MethodChannel ┌──────────────────┐
│ Flutter (Dart) │ ◄────────────────────► │ Native (各平台) │
│ amps_sdk/lib │ invokeMethod / 回调 │ manager/*.kt 等 │
└─────────────────┘ └──────────────────┘
常用通道类型:
| 类型 | 用途 | amps_sdk 是否使用 |
|---|---|---|
| MethodChannel | 方法调用 + 离散事件回调 | ✅ 主通道 amps_sdk |
| EventChannel | 持续数据流(传感器、进度) | ❌ 广告事件是离散的,用 MethodChannel 反向调用即可 |
| PlatformView | 在 Flutter 布局里嵌入原生 View | ✅ 原生模板 / 自渲染信息流 |
广告插件和普通插件最大的区别:不是调一次就结束,而是 load → render → show → click → close 一长串异步回调,且可能多路广告同时进行。
二、amps_sdk 整体分层
媒体 App (example/)
│
▼
lib/ ← Dart 对外 API
├── amps_sdk.dart ← 全局 MethodChannel
├── controller/ ← 各广告类型 Controller
├── data/ ← 配置、常量、Dispatcher
└── native_widget.dart 等 ← PlatformView 封装
│
▼
android/ ios/ ohos/ ← 三端原生实现
├── manager/ ← 按广告类型拆分
├── data/InstanceChannelHelper
└── view/ ← PlatformView Factory
│
▼
AMPS ADN SDK (biz.beizi.adn) ← 底层广告 SDK
支持的广告形态:
| 模块 | Dart 类 | 展示方式 |
|---|---|---|
| 初始化 | AMPSAdSDK | — |
| 开屏 | AMPSSplashAd | showAd() 全屏覆盖 |
| 插屏 | AMPSInterstitialAd | showAd() 全屏覆盖 |
| 原生模板 | AMPSNativeAd | NativeWidget 嵌入列表 |
| 自渲染 | AMPSNativeAd(unified) | UnifiedWidget + 布局 DSL |
三、MethodChannel:一条通道走天下
3.1 通道名四端对齐
Dart 侧定义唯一主通道:
// lib/amps_sdk.dart
class AmpsSdk {
static const MethodChannel channel = MethodChannel('amps_sdk');
}
lib/common.dart 里集中维护 方法名、回调名、PlatformView ID,Android / iOS / OHOS 各有一份对应常量。这是跨端联调成本最低的做法——改一处,四端同步。
主通道负责两类通信:
- Dart → Native:
channel.invokeMethod('AMPSSplashAd_load', args) - Native → Dart:
channel.invokeMethod('onRenderOk', args)(反向调用)
3.2 参数怎么传
复杂配置不适合 positional 参数。amps_sdk 用 Builder + Map:
final config = AMPSBuilder("your_app_id")
.setAppName("测试 App")
.setDebugSetting(true)
.setAdCustomController(AMPSCustomController(param: ...))
.build();
await AmpsSdk.channel.invokeMethod(
AMPSAdSdkMethodNames.init,
config.toMap(testModel),
);
Native 侧用 Converter 把 Map 转成 SDK 需要的对象。Map 的 key 在 amps_sdk_api_keys.dart 里统一定义,避免字符串拼写错误。
3.3 Init 回调:不带 instanceId
初始化是全局单例行为,回调直接传 flat map:
// Native → Dart
{ "code": 1001, "message": "init failed" }
// Dart 处理
case AMPSInitChannelMethod.initFailed:
final map = call.arguments as Map?;
_callBack?.initFailed?.call(map?['code'], map?['message']);
四、Dart 层设计:五个模块 + 一个 Dispatcher
4.1 五个 Controller,一种调用风格
和原生 SDK 对齐,Flutter 端也拆成五个模块:
// 初始化
AMPSAdSDK().init(sdkConfig, initCallBack);
// 开屏
final splash = AMPSSplashAd(config: options, mCallBack: callback);
splash.load();
splash.showAd(splashBottomWidget: bottom);
// 插屏 — 同上
final interstitial = AMPSInterstitialAd(config: options, mCallBack: callback);
// 原生 / 自渲染
final native = AMPSNativeAd(config: options, mCallBack: callback);
native.load();
// renderSuccess 后
NativeWidget(native, adId: adId);
Flutter 没有 interface,用 typedef + 回调类 代替:
class AdCallBack {
final VoidCallback? onRenderOk;
final void Function(int? code, String? msg)? onLoadFailure;
final VoidCallback? onAdClosed;
// ...
}
4.2 核心问题:setMethodCallHandler 会被覆盖
如果每个 Controller 都写:
AmpsSdk.channel.setMethodCallHandler((call) { ... });
后注册的会覆盖先注册的。典型场景:先 load 开屏,再 load 插屏,开屏的所有回调全丢。
这是广告插件最常见的 Dart 层 bug。
4.3 解法:AmpsChannelDispatcher
全局只注册 一次 handler,各模块 register 自己的处理函数:
class AmpsChannelDispatcher {
static const String kInstanceId = 'instanceId';
static const String kData = 'data';
static final List<AmpsChannelHandler> _handlers = [];
static void register(AmpsChannelHandler handler) {
_ensureInstalled();
if (!_handlers.contains(handler)) _handlers.add(handler);
}
static void _ensureInstalled() {
AmpsSdk.channel.setMethodCallHandler((call) async {
for (final h in List<AmpsChannelHandler>.from(_handlers)) {
try { await h(call); } catch (_) {}
}
});
}
static String? extractInstanceId(MethodCall call) {
final args = call.arguments;
if (args is Map) return args[kInstanceId] as String?;
return null;
}
}
Init 注册一次;Splash / Interstitial / Native 各自注册 _handleChannelCall,只处理本类型的 call.method。
4.4 多实例:instanceId 协议
单例 Manager 只能承载一路广告。媒体 App 常见需求:
- 开屏 A 展示中,B 已在后台 load 好
- Feed 里多个原生广告并行
约定统一协议:
| 方向 | 格式 |
|---|---|
| Dart → Native | { ...config, instanceId: 'splash_xxx_1' } |
| Native → Dart | { instanceId: 'splash_xxx_1', data: <payload> } |
Controller 实现模式:
class AMPSSplashAd {
final String _instanceId = _generateInstanceId();
static final Map<String, AMPSSplashAd> _instances = {};
AMPSSplashAd({required this.config, this.mCallBack}) {
_instances[_instanceId] = this;
AmpsChannelDispatcher.register(_handleChannelCall);
}
void load() {
AmpsSdk.channel.invokeMethod(AMPSAdSdkMethodNames.splashLoad, {
...config.toMap(),
AmpsChannelDispatcher.kInstanceId: _instanceId,
});
}
static Future<void> _handleChannelCall(MethodCall call) async {
final id = AmpsChannelDispatcher.extractInstanceId(call);
if (id == null) return;
final ad = _instances[id];
// 根据 call.method 触发 ad.mCallBack
}
}
每个实例有唯一 ID,回调通过 _instances[id] 路由,互不干扰。
五、Native 层设计:EventManager + Manager + Helper
5.1 为什么不建多个 Plugin
有人用多个 Plugin(每个广告类型一个 MethodChannel)。问题是 GeneratedPluginRegistrant 默认只注册主 Plugin,多 Plugin 容易丢注册。
推荐方案:一个 Plugin + 一个 EventManager + 多个 Manager。
AmpsSdkPlugin
└── AMPSEventManager(唯一 MethodChannel)
├── AMPSSDKInitManager
├── AMPSSplashManager
├── AMPSInterstitialManager
└── AMPSNativeManager
Inbound 路由(Dart 调 Native):
override fun onMethodCall(call: MethodCall, result: Result) {
when {
InitMethodNames.contains(call.method) ->
AMPSSDKInitManager.getInstance().handleMethodCall(call, result)
SplashMethodNames.contains(call.method) ->
AMPSSplashManager.getInstance().handleMethodCall(call, result)
InterstitialMethodNames.contains(call.method) ->
AMPSInterstitialManager.getInstance().handleMethodCall(call, result)
NativeMethodNames.contains(call.method) ->
AMPSNativeManager.getInstance().handleMethodCall(call, result)
else -> result.notImplemented()
}
}
Outbound 回调(Native 调 Dart)统一走:
AMPSEventManager.getInstance().sendMessageToFlutter(method, args)
5.2 Manager 多实例 Map
单例字段无法承载多路广告:
// ❌ B 会覆盖 A
private var mSplashAd: AMPSSplashAd? = null
改为按 instanceId 隔离:
private class AdEntry(val instanceId: String) {
var mSplashAd: AMPSSplashAd? = null
val containerTag = "splash_main_container_tag_$instanceId"
}
private val ads = mutableMapOf<String, AdEntry>()
private fun getOrCreateEntry(instanceId: String): AdEntry {
return ads.getOrPut(instanceId) { AdEntry(instanceId) }
}
load:解析instanceId,创建 Entry,发起 SDK loadshowAd:按 instance 找 Entry,在 decorView 上挂独立容器(tag 隔离)onAdClosed:清理对应容器,释放 Entry
iOS 用嵌套 DelegateHandler 解决 SDK delegate 无法区分实例;OHOS 用 ArkTS class + Map,逻辑一致。
5.3 InstanceChannelHelper:Outbound 统一封装
Native 回调 Flutter 时必须带 instanceId,三端同构:
// Android
object InstanceChannelHelper {
fun send(method: String, instanceId: String, data: Any? = null) {
AMPSEventManager.getInstance().sendMessageToFlutter(
method,
mapOf("instanceId" to instanceId, "data" to data)
)
}
}
SDK 回调里:
override fun onAmpsAdLoaded() {
InstanceChannelHelper.send(ON_LOAD_SUCCESS, instanceId)
InstanceChannelHelper.send(ON_RENDER_OK, instanceId)
}
override fun onAmpsAdDismiss() {
cleanupViewsAfterAdClosed(instanceId)
InstanceChannelHelper.send(ON_AD_CLOSED, instanceId)
}
iOS 有 InstanceChannelHelper.swift,OHOS 有 InstanceChannelHelper.ets,协议完全相同。
六、两种展示范式:这是广告插件的分水岭
广告插件和普通插件最大的架构分叉:全屏广告 和 嵌入信息流 走完全不同的桥接路径。
范式 A:全屏 —— load + showAd
开屏、插屏
final splash = AMPSSplashAd(config: options, mCallBack: callback);
splash.load();
// onRenderOk 后
splash.showAd(splashBottomWidget: bottomWidget);
Native 在 Activity 的 decorView(iOS 是当前 VC)上动态挂载容器,不占 Flutter 布局树。关闭时 Native 自己 removeView,再回调 onAdClosed。
特点:
- 不需要 PlatformView
- 展示层级在 Flutter 之上
- 适合启动页、弹窗类广告
范式 B:嵌入 —— load + PlatformView
原生模板、自渲染信息流
nativeAd.load();
// renderSuccess(adId) 后
NativeWidget(nativeAd, adId: adId);
AndroidView(
viewType: AMPSPlatformViewRegistry.ampsSdkNativeViewId,
creationParams: {"adId": adId, "width": width},
onPlatformViewCreated: _onPlatformViewCreated,
);
特点:
- 广告嵌在 ListView / Column 里
- 每个 creative 分配 UUID
adId - 关闭时必须知道删哪一条 feed item
这里有两个 ID,职责不同:
| ID | 层级 | 作用 |
|---|---|---|
instanceId | 会话级 | 区分「第几路 load 请求」,路由 MethodChannel 回调 |
adId | 创意级 | 区分「哪一条广告素材」,PlatformView 创建参数、关闭时删 item |
范式 C:Widget 内嵌 + 独立 Channel(Legacy)
SplashWidget / InterstitialWidget 在 PlatformView 创建后,会注册独立通道:
MethodChannel('biz.beizi.adn/splash_view_id$id')
此路径回调 不带 全局 instanceId envelope,适合单实例 Demo。生产环境多实例并行,推荐主通道 + Dispatcher 方案。
七、自渲染(Unified):布局 DSL → Native 动态建 View
自渲染是 amps_sdk 比普通插件多出来的一层:Flutter 描述布局,Native 按 DSL 动态创建 ImageView、TextView、CloseButton 等。
7.1 Dart 描述布局
NativeUnifiedWidget(
height: 128,
backgroundColor: '#F0EDF4',
children: [
UnifiedMainImgWidget(width: 120, height: 90, ...),
UnifiedTitleWidget(textSize: 14, ...),
UnifiedCloseWidget(imagePath: 'assets/images/close.png'),
DownLoadWidget(..., downloadListener: listener),
],
)
toMap() 作为 PlatformView 的 creationParams 传给 Native。
7.2 Native 渲染链路
UnifiedWidget (Dart)
→ PlatformView creationParams
→ AMPSUnifiedView (Native Factory)
→ NativeUnifiedModule
→ AmpsUnifiedFrameLayout.render()
按 type 创建子 View → bindAdToRootContainer
7.3 关闭回调的坑
多实例改造后,若自渲染 View 层仍 sendMessage(onAdClosed, adId) 不带 instanceId,Dart Dispatcher 会直接丢弃回调 → feed 卡片不删、PlatformView 变成空壳 → 底部出现白条。
修复要点:
AdUnifiedWrapperManager维护adId → instanceId映射AmpsUnifiedFrameLayout所有回调走InstanceChannelHelper.send(method, instanceId, adId)- Flutter 侧
onAdClosed按adId从列表移除 item - Example 可加 Flutter 兜底关闭按钮(原生不回调时手动移除)
八、完整时序:从 load 到 close
以开屏双实例为例:
sequenceDiagram
participant App as Flutter App
participant A as AMPSSplashAd(A)
participant B as AMPSSplashAd(B)
participant Disp as AmpsChannelDispatcher
participant Ch as MethodChannel
participant Mgr as AMPSSplashManager
App->>A: load() instanceId=A
App->>B: load() instanceId=B
A->>Ch: splashLoad + instanceId
B->>Ch: splashLoad + instanceId
Ch->>Mgr: handleSplashLoad ×2
Mgr-->>Ch: onRenderOk {instanceId:A}
Ch->>Disp: fan-out
Disp->>A: callback.onRenderOk
App->>A: showAd()
Mgr-->>Ch: onAdClosed {instanceId:A}
Disp->>A: callback.onAdClosed
App->>B: showAd()
Example 里的验证逻辑:
_splashAdA = AMPSSplashAd(config: options, mCallBack: callbackA);
_splashAdB = AMPSSplashAd(config: options, mCallBack: callbackB);
debugPrint('A instanceId=${_splashAdA!.instanceId}');
_splashAdA!.load();
_splashAdB!.load();
// A onRenderOk → showAd(A)
// A onAdClosed → showAd(B)
验证标准:Log 里两个不同 instanceId;A 关闭后 B 正常接续,无回调串台。
九、三端一致性要点
| 层级 | Android | iOS | HarmonyOS |
|---|---|---|---|
| 入口 | AmpsSdkPlugin.kt | AmpsSdkPlugin.swift | AmpsSdkPlugin.ets |
| 分发 | AMPSEventManager | 同名 | 同名 |
| 多实例 | Map<instanceId, AdEntry> | 嵌套 DelegateHandler | ArkTS class + Map |
| 回调封装 | InstanceChannelHelper.kt | .swift | .ets |
| PlatformView | PlatformViewFactory | FlutterPlatformView | PlatformView |
OHOS 特别注意:PlatformView 里的 adId 必须是实例字段,不能是 static——否则多路原生广告会共用同一个 adId,关闭时串台。
十、开发环境与项目创建(精简版)
广告插件常需三端 Flutter SDK,版本不一致时用 FVM 管理:
dart pub global activate fvm
fvm install 3.35.3 # Android / iOS
fvm use 3.35.3
# HarmonyOS 需 clone OHOS 版 Flutter
git clone -b 3.22.0-ohos https://gitcode.com/openharmony-tpc/flutter_flutter.git
fvm flutter create --template=plugin --platforms=android,ios,ohos amps_sdk
各端 IDE 打开路径:
| 平台 | IDE | 路径 |
|---|---|---|
| Android | Android Studio | example/android |
| iOS | Xcode | example/ios/Runner.xcworkspace |
| HarmonyOS | DevEco Studio | example/ohos |
原生 SDK 依赖建议发布到 Maven / CocoaPods / OHPM,避免让接入方手动拷贝 AAR。
十一、Checklist:上线前自查
Dart 层
- 禁止各 Controller 直接
AmpsSdk.channel.setMethodCallHandler - 除 Init 外,所有 invoke / 回调带
instanceId - 信息流关闭用
adId删 item;PlatformView 用ValueKey('${label}_$adId') - Controller dispose 时从
_instances移除并 unregister handler
Native 层
- Manager 内禁止单字段
var xxxAd承载多会话 - 广告回调统一
InstanceChannelHelper.send - 自渲染 View 发回调前能解析
instanceId - PlatformView dispose 清理 WrapperManager
- showAd 容器用唯一 tag,close 时 removeView
联调
- 双实例 A/B 页面:并行 load、顺序 show、回调不串
- 自渲染关闭后 feed 无留白
- 三端 method 名 / 回调名 / PlatformView ID 一致
十二、总结
Flutter 广告插件的核心,不是「调通一个 MethodChannel」,而是解决四件事:
- 通道分工 — 一个主 MethodChannel 负责命令和离散回调;PlatformView 负责嵌入展示
- Dart Dispatcher — 全局一次 handler 注册,多模块 fan-out,避免回调覆盖
- instanceId 协议 — Dart 和 Native 两端 Map 隔离,支撑多路广告并行
- 两种展示范式 — 全屏
showAd与嵌入 PlatformView 分轨设计;自渲染额外维护 adId ↔ instanceId 映射
amps_sdk 把这套架构落到了 Android、iOS、HarmonyOS 三端,Example 里提供了开屏 / 插屏 / 原生 / 自渲染的双实例验证页。照着这个结构做,你的插件从 Demo 到生产会少走很多弯路。