在 Flutter 中,插件也称为 package,使用 插件的目的是为了达到模块化和代码复用。一个最小化的package包含了两部分: * 一个pubspec.yaml文件:一个元数据文件,声明了声明了package的名称、版本、作者等信息。插件类型包括两种:

  • Dart packages:这是一个只有dart代码的package,里面包含了flutter的特定功能,所以它依赖于flutter的framework,也决定了它只能用在flutter上。
  • Plugin packages:这是一个既包含了dart代码编写的api,又包含了平台(Android/IOS)特定实现的package,可以被Android和ios调用。

初始化插件

创建插件
flutter create —template=plugin —org com.sky -i swift flutter_native_webview
# 检查插件
flutter packages pub publish —dry-run
# 发布插件
flutter packages pub publish

Flutter 插件三端逻辑

这里以封装 Native WebView 实现 Flutter 插件 flutter_native_webview 为例

初始化项目

flutter create —template=plugin —org com.sky -i swift flutter_native_webview

其中 pubspec.yaml 文件会定义组件的 名称,版本,作者,依赖, android/ios 入口代码

image.png

插件实现

  1. package com.sky.flutter_native_webview;
  2. import io.flutter.plugin.common.PluginRegistry.Registrar;
  3. import io.flutter.plugin.common.StandardMessageCodec;
  4. /** FlutterNativeWebviewPlugin */
  5. public class FlutterNativeWebviewPlugin {
  6. /** Plugin registration. */
  7. public static void registerWith(Registrar registrar) {
  8. registrar.platformViewRegistry().registerViewFactory("com.sky.flutter.NativeWebView", new NativeWebViewFactory(new StandardMessageCodec()));
  9. }
  10. }
  • 实现 iOS 入口代码, 创建插件时,默认会创建插件的注册入口,只需要实现 Native WebView 注册即可
  1. import Flutter
  2. public class SwiftFlutterNativeWebviewPlugin: NSObject, FlutterPlugin {
  3. public static func register(with registrar: FlutterPluginRegistrar) {
  4. registrar.register(FlutterWebViewFactory(), withId: "com.sky.flutter.NativeWebView");
  5. }
  6. }
  • Flutter 中使用 flutter_native_webview 组件

需要在项目的 pubspec.yaml 的 dependencies 节点添加 flutter_native_webview 依赖

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_native_webview/flutter_native_webview.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatefulWidget {
  5. @override
  6. _MyAppState createState() => _MyAppState();
  7. }
  8. class _MyAppState extends State<MyApp> {
  9. @override
  10. Widget build(BuildContext context) {
  11. return MaterialApp(
  12. home: Scaffold(
  13. appBar: AppBar(
  14. title: const Text('Plugin example app'),
  15. ),
  16. body: NativeWebView("https://pub.dev/"),
  17. ),
  18. );
  19. }
  20. }