Flutter 自定义插件端到端实践总结

Flutter 自定义插件端到端实践总结

环境:Windows 11 / Flutter 3.47.7 (stable) / Android SDK 36.0.0 / JDK 21 (JBR) 真机:BRA AL00 (Android 12, API 31, arm64) 日期:2026-12-17


一、整体流程概览

arduino 复制代码
创建插件工程 → 编写三层代码 → 创建消费工程 → path 引入插件 → pub get → analyze → build apk → adb install 真机

最终目录结构:

makefile 复制代码
D:\ArkUI-X\error\flutter\
├── my_custom_plugin\              # 插件工程
│   ├── lib\                        # Dart 接口层(3 个文件)
│   │   ├── my_custom_plugin.dart
│   │   ├── my_custom_plugin_platform_interface.dart
│   │   └── my_custom_plugin_method_channel.dart
│   ├── android\                    # Kotlin 原生层
│   │   └── src\main\kotlin\com\example\my_custom_plugin\MyCustomPlugin.kt
│   ├── example\                    # 内置示例工程
│   └── pubspec.yaml               # 插件声明(plugin.platforms.android)
│
├── my_app\                         # 消费工程
│   ├── lib\main.dart              # 调用 getPlatformVersion()
│   ├── android\                    # 消费工程 Android 配置
│   │   ├── gradle\wrapper\gradle-wrapper.properties
│   │   ├── settings.gradle.kts
│   │   ├── build.gradle.kts
│   │   └── gradle.properties
│   └── build\app\outputs\flutter-apk\app-debug.apk  # 编译产物 (143.52 MB)
│
└── flutter自定义插件端到端实践总结.md   # 本文档

二、分步执行记录

步骤 1:创建插件工程

命令:

bash 复制代码
flutter create --template=plugin --platforms=android -a kotlin my_custom_plugin

参数说明:

参数 作用
flutter create Flutter 项目创建命令
--template=plugin 使用插件模板(自动生成 MethodChannel 桥接骨架)
--platforms=android 只生成 Android 平台的原生代码目录(不生成 iOS)
-a kotlin Android 端使用 Kotlin 语言
my_custom_plugin 插件项目名称

输出: 生成 56 个文件,插件代码在 lib/my_custom_plugin.dart,原生代码在 android/ 目录下。


步骤 2:确认插件三层代码

Flutter 插件模板默认以 getPlatformVersion 为示例,自动生成完整的三层桥接代码,无需额外编写。

2a. Dart 接口层 --- lib/my_custom_plugin.dart
dart 复制代码
import 'my_custom_plugin_platform_interface.dart';

class MyCustomPlugin {
  Future<String?> getPlatformVersion() {
    return MyCustomPluginPlatform.instance.getPlatformVersion();
  }
}

作用: 对外暴露的公开 API,消费工程通过此类调用 getPlatformVersion(),内部委托给 platform interface。

2b. 平台接口层 --- lib/my_custom_plugin_platform_interface.dart
dart 复制代码
abstract class MyCustomPluginPlatform extends PlatformInterface {
  MyCustomPluginPlatform() : super(token: _token);
  static final Object _token = Object();
  static MyCustomPluginPlatform _instance = MethodChannelMyCustomPlugin();

  static MyCustomPluginPlatform get instance => _instance;
  static set instance(MyCustomPluginPlatform instance) {
    PlatformInterface.verifyToken(instance, _token);
    _instance = instance;
  }

  Future<String?> getPlatformVersion() {
    throw UnimplementedError('platformVersion() has not been implemented.');
  }
}

作用: 定义抽象接口契约,默认实现指向 MethodChannelMyCustomPlugin。通过 PlatformInterface 机制确保只有合法实现能替换默认实例,支持 mock 测试。

2c. Method Channel 实现层 --- lib/my_custom_plugin_method_channel.dart
dart 复制代码
class MethodChannelMyCustomPlugin extends MyCustomPluginPlatform {
  @visibleForTesting
  final methodChannel = const MethodChannel('my_custom_plugin');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }
}

作用: 通过名为 'my_custom_plugin' 的 MethodChannel 向原生端发送 'getPlatformVersion' 方法调用,接收原生返回的字符串结果。

2d. Android Kotlin 原生层 --- android/.../MyCustomPlugin.kt
kotlin 复制代码
class MyCustomPlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var channel: MethodChannel

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "my_custom_plugin")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}

作用: 在 onAttachedToEngine 中注册同名 MethodChannel,在 onMethodCall 中按方法名分发。收到 "getPlatformVersion" 时返回 Android <版本号>,未知方法返回 notImplemented。

2e. 插件 pubspec.yaml 配置
yaml 复制代码
flutter:
  plugin:
    platforms:
      android:
        package: com.example.my_custom_plugin
        pluginClass: MyCustomPlugin

作用: 声明插件的 Android 平台入口,Flutter 工具链据此自动将 MyCustomPlugin 类注册到 Flutter 引擎。


步骤 3:创建消费工程

命令:

bash 复制代码
flutter create my_app

作用: 创建标准 Flutter 应用工程(默认 application 模板),包含 Android 平台支持。

输出: 生成 131 个文件,应用代码在 lib/main.dart。


步骤 4:引入插件 + 编写调用代码

4a. 在 my_app/pubspec.yaml 中添加 path 依赖
yaml 复制代码
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8

  my_custom_plugin:
    path: ../my_custom_plugin    # 关键:本地路径引入

作用: 告诉 pub 包管理器从本地相对路径 ../my_custom_plugin 加载插件源码,而非从 pub.dev 下载。修改插件代码后即时生效,无需发布。

4b. 重写 my_app/lib/main.dart 调用插件
dart 复制代码
import 'package:flutter/material.dart';
import 'package:my_custom_plugin/my_custom_plugin.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Plugin Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: '插件调用示例'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _myCustomPlugin = MyCustomPlugin();
  String _version = '点击按钮获取系统版本';

  Future<void> _getPlatformVersion() async {
    String? version = await _myCustomPlugin.getPlatformVersion();
    setState(() {
      _version = version ?? '获取失败';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('当前系统版本:', style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 8),
            Text(_version, style: Theme.of(context).textTheme.headlineMedium),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getPlatformVersion,
        tooltip: '获取版本',
        child: const Icon(Icons.android),
      ),
    );
  }
}

作用: 导入插件包,创建 MyCustomPlugin 实例,点击 FAB 按钮触发 getPlatformVersion() 异步调用,通过 setState 将返回的系统版本显示在界面上。


步骤 5:依赖解析

命令:

bash 复制代码
cd my_app
flutter pub get

作用: 解析 pubspec.yaml 声明的依赖,从本地路径拉取插件源码到包缓存,生成 pubspec.lock。

输出:

diff 复制代码
+ my_custom_plugin 0.0.1 from path ..\my_custom_plugin
+ plugin_platform_interface 2.1.8
Changed 2 dependencies!

from path ..\my_custom_plugin 确认本地路径引用生效。


步骤 6:Dart 静态分析

命令:

bash 复制代码
flutter analyze

作用: 对 Dart 代码做静态分析,检查类型错误、未使用导入、lint 规范等。

输出:

scss 复制代码
No issues found! (ran in 4.8s)

步骤 7:Android 编译构建

命令:

bash 复制代码
flutter build apk --debug

作用: 编译 Dart 代码 → 生成 Kotlin 字节码 → 打包为 debug APK。验证 Dart ↔ Kotlin MethodChannel 桥接两端代码均能正确编译链接。使用 --debug 跳过签名和混淆,加速构建。

输出:

lua 复制代码
Running Gradle task 'assembleDebug'...  442.3s
√ Built build\app\outputs\flutter-apk\app-debug.apk

APK 大小 143.52 MB(debug 包含调试符号,体积正常)。


步骤 8:安装到真机

命令:

bash 复制代码
adb install -r build\app\outputs\flutter-apk\app-debug.apk

作用: 将 APK 推送到已连接的 Android 设备并安装。-r 表示覆盖安装(保留数据)。

输出:

arduino 复制代码
List of devices attached
TCS0123412000475    device

Performing Streamed Install
Success

安装成功。在真机上打开应用,点击右下角浮动按钮,界面显示 Android 12(真机系统版本),验证 MethodChannel 桥接端到端生效。


三、环境适配(国内网络问题)

问题现象

flutter build apk 首次执行时报错:

makefile 复制代码
java.net.UnknownHostException: services.gradle.org

Gradle wrapper 尝试从 services.gradle.org 下载 Gradle 发行版,但该域名(Cloudflare IP 104.16.73.101)在国内被墙,Java 进程 DNS 解析失败。同时 google()、mavenCentral() 等 Maven 仓库也可能存在类似问题。

根因分析

问题 原因
services.gradle.org 不可达 Cloudflare IP 被 GFW 拦截,PowerShell 和 Java 均无法连接
Java UnknownHostException Java 优先使用 IPv6,但本机 IPv6 连接不通;部分镜像只有 AAAA 记录
mirrors.cloud.tencent.com IPv6 only CNAME 链最终只返回 AAAA 记录(240e:954:...),Java 无法解析

解决方案

系统已有缓存的 Gradle 9.4.0 发行版(位于 ~/.gradle/wrapper/dists/),通过以下四处修改绕过所有 DNS 问题:

修改 1:gradle-wrapper.properties --- 改为本地 file:/// 路径
properties 复制代码
# 原始(需要 DNS 下载):
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip

# 修改后(指向本地缓存,零 DNS 依赖):
distributionUrl=file\:///C:/Users/cclgt/.gradle/wrapper/dists/gradle-9.4.0-bin/7muejuya9k0fqlnu8kjubikgh/gradle-9.4.0-bin.zip

作用: Gradle wrapper 直接从本地文件加载发行版,完全绕过 DNS 下载环节。

修改 2:settings.gradle.kts --- Maven 仓库改阿里云镜像
kotlin 复制代码
// 原始:
repositories {
    google()
    mavenCentral()
    gradlePluginPortal()
}

// 修改后:
repositories {
    maven("https://maven.aliyun.com/repository/google")
    maven("https://maven.aliyun.com/repository/central")
    maven("https://maven.aliyun.com/repository/gradle-plugin")
}

作用: Gradle 插件解析(AGP、Kotlin、flutter-plugin-loader)走阿里云镜像(IPv4: 36.42.78.57),国内直连。

修改 3:build.gradle.kts --- 项目级依赖改阿里云镜像
kotlin 复制代码
// 原始:
allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

// 修改后:
allprojects {
    repositories {
        maven("https://maven.aliyun.com/repository/google")
        maven("https://maven.aliyun.com/repository/central")
    }
}

作用: 项目所有子模块的 Maven 依赖统一走阿里云镜像。

修改 4:gradle.properties --- 强制 IPv4
properties 复制代码
# 原始:
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError

# 修改后(追加 IPv4 偏好):
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true

作用: 强制 Gradle daemon 使用 IPv4 协议栈,避免 IPv6 连接不通导致的 DNS 解析失败。

运行时还需设置环境变量(Gradle wrapper 进程用):

powershell 复制代码
$env:JAVA_OPTS="-Djava.net.preferIPv4Stack=true"
$env:GRADLE_OPTS="-Djava.net.preferIPv4Stack=true"
flutter build apk --debug

环境适配总结

修改文件 修改内容 解决的问题
gradle-wrapper.properties URL 改 file:/// 本地路径 Gradle 发行版下载 DNS 失败
settings.gradle.kts 3 个仓库改阿里云镜像 Gradle 插件 Maven 仓库不可达
build.gradle.kts 2 个仓库改阿里云镜像 项目依赖 Maven 仓库不可达
gradle.properties 追加 preferIPv4Stack=true Java IPv6 DNS 解析失败

四、关键技术点

MethodChannel 桥接流程

scss 复制代码
消费工程 Dart 代码                    原生 Android 代码
     │                                      │
     │  MyCustomPlugin()                     │
     │  .getPlatformVersion()                │
     │         │                             │
         ▼                                    │
  MethodChannelMyCustomPlugin                 │
  methodChannel.invokeMethod(                 │
    'getPlatformVersion'  ──────────────►  onMethodCall(call)
  )                                            │ call.method == "getPlatformVersion"
         │                                    │
    ◄─────────────── result.success(          │
  返回 String         "Android 12")            │
     │                                      │
     ▼                                      │
  setState() 更新 UI                          │

path 依赖 vs Git 依赖 vs pub.dev

方式 适用场景 优点 缺点
path: ../my_custom_plugin 本地开发调试 改动即时生效,零发布成本 路径绑定,团队需统一目录结构
git: {url, ref} 团队协作 可版本锁定,团队成员拉取一致 需推送 Git 仓库,调试需 pub get 刷新
my_custom_plugin: ^1.0.0 公开发布 版本管理规范,社区可复用 需搭建/使用 pub.dev,发布流程重

五、完整命令清单

bash 复制代码
# 1. 创建插件工程
flutter create --template=plugin --platforms=android -a kotlin my_custom_plugin

# 2. 创建消费工程
flutter create my_app

# 3. 在 my_app/pubspec.yaml 添加:
#    my_custom_plugin:
#      path: ../my_custom_plugin

# 4. 编写 my_app/lib/main.dart 调用插件

# 5. 依赖解析
cd my_app
flutter pub get

# 6. 静态分析
flutter analyze

# 7. 构建 APK(国内需先改镜像配置)
$env:JAVA_OPTS="-Djava.net.preferIPv4Stack=true"
$env:GRADLE_OPTS="-Djava.net.preferIPv4Stack=true"
flutter build apk --debug

# 8. 安装到真机
adb install -r build\app\outputs\flutter-apk\app-debug.apk
相关推荐
耀耀_很无聊12 分钟前
17_Spring Boot 使用 MDC 实现 TraceId 日志追踪
java·spring boot·后端
二月龙16 分钟前
iOS 网络层封装:Alamofire 二次封装最佳实践
后端
喵个咪19 分钟前
GoWind Admin 拆解:智能问数——从一句自然语言到一张可信图表
后端·llm·go
孟陬1 小时前
Foobar 技术周刊 #003:黄仁勋的三段吃瓜和回归,抛开事实不谈(嘿嘿)让全人类 AGI 进程得以继续
前端·后端·程序员
程序员小杰@2 小时前
SpringBoot + SpringCloudAlibaba 日志 & 链路追踪 完整总结
java·spring boot·后端
PFinal社区_南丞3 小时前
别再手写 Ubuntu 配置了!我用 AI 搓了个免费纯前端服务器配置生成器:ubuntu.pub
后端
想不到一个好的ID4 小时前
G1 垃圾回收器
后端
ZhengEnCi4 小时前
模型配置页怎么做:多模型备用链自动切换,API Key 加密存储只显示掩码
后端·llm·ai编程
Mk598785 小时前
一人公司用 FastAPI+Vue3 搭工作台,我把 5 个阶段跑通了
vue.js·后端