一统天下 flutter - 插件: flutter 使用 ios 原生控件,并做数据通信

源码 https://github.com/webabcd/flutter_demo
作者 webabcd

一统天下 flutter - 插件: flutter 使用 ios 原生控件,并做数据通信

示例如下:

lib\plugin\plugin2.dart

/*
 * 插件
 * 本例用于演示 flutter 使用 android/ios 原生控件,并做数据通信
 *
 * 一、android 插件开发
 * 1、主 flutter 项目要先在 android 平台中运行一下
 * 2、在 android 文件夹上,使用右键菜单,然后选择 Flutter -> Open Android module in Android Studio 即可开发插件
 * 3、参见 /android/app/src/main/kotlin/com/example/flutter_demo/MainActivity.kt
 *
 * 二、ios 插件开发
 * 1、主 flutter 项目要先在 ios 平台中运行一下
 * 2、在 android studio 或 visual studio code 中执行如下逻辑
 *    cd ios
 *    pod install
 * 3、用 xcode 中打开 /ios/Runner.xcworkspace 即可开发插件
 * 4、参见 /ios/Runner/AppDelegate.swift
 *
 *
 * 注:插件中实现的功能不支持 flutter 的 hot reload
 */

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../helper.dart';

class Plugin2Demo extends StatefulWidget {
  const Plugin2Demo({Key? key}) : super(key: key);

  @override
  _Plugin2DemoState createState() => _Plugin2DemoState();
}

class _Plugin2DemoState extends State<Plugin2Demo> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: const Text('title'),
      ),
      body: const _MyWidget()
    );
  }
}


class _MyWidget extends StatefulWidget {
  const _MyWidget({Key? key}) : super(key: key);

  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<_MyWidget> {

  /// 用于保存从 android/ios 发送到 flutter 的数据
  String _nativeToFlutterMessage = '';
  /// 用于控制 android/ios 和 flutter 通信的 controller
  final _controller = _MyViewController();

  @override
  void initState() {

    _controller.addListener(() {
      setState(() {
        _nativeToFlutterMessage = _controller.nativeToFlutterMessage;
      });
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Expanded(
          child: Container(
            color: Colors.red,
            child: _buildNativeView(),
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.green,
            child: _buildFlutterView(),
          ),
        ),
      ],
    );
  }

  /// 嵌入到 flutter 中的 android/ios 的 view
  Widget _buildNativeView() {
    return _MyNativeView(
      controller: _controller,
    );
  }

  Widget _buildFlutterView() {
    return Stack(
      alignment: AlignmentDirectional.bottomCenter,
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("native to flutter: $_nativeToFlutterMessage"),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                _controller.flutterToNative("${DateTime.now().millisecondsSinceEpoch}");
              },
              child: const Text('发送数据给 Native'),
            ),
          ],
        ),
        const Padding(
          padding: EdgeInsets.only(bottom: 15),
          child: Text(
            'Flutter - View',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }
}


/// 嵌入到 flutter 中的 android/ios 的 view
class _MyNativeView extends StatefulWidget {
  final _MyViewController controller;

  const _MyNativeView({required this.controller, Key? key}) : super(key: key);

  @override
  _MyNativeViewState createState() => _MyNativeViewState();
}

class _MyNativeViewState extends State<_MyNativeView> {

  @override
  Widget build(BuildContext context) {

    /// 判断是否为 web 环境要用 kIsWeb
    /// 如果在 web 环境使用 Platform.xxx 的话会报错的
    if (kIsWeb) {
      return const MyText("不支持 web 环境");
    }

    if (Platform.isAndroid) {
      /// 嵌入到 flutter 中的 android 的 view(相关的插件在 android/app/src/main/kotlin/com/example/flutter_demo/MyFlutterPlugin2.kt)
      return AndroidView(
        viewType: 'com.webabcd.flutter/myview',                           /// 需要嵌入的 view 的标识(这是在插件中定义的)
        onPlatformViewCreated: _onPlatformViewCreated,                    /// 传给插件的初始参数
        creationParams: const <String, dynamic>{'k1': 'p1', 'k2': 'p2'},  /// 传给插件的初始参数的编码方式
        creationParamsCodec: const StandardMessageCodec(),                /// 需要嵌入的 view 创建后触发的事件
      );
    }

    if (Platform.isIOS) {
      /// 嵌入到 flutter 中的 ios 的 view(相关的插件在 ios/Runner/MyFlutterPlugin2.swift)
      return UiKitView(
        viewType: 'com.webabcd.flutter/myview',                           /// 需要嵌入的 view 的标识(这是在插件中定义的)
        creationParams: const <String, dynamic>{'k1': 'p1', 'k2': 'p2'},  /// 传给插件的初始参数
        creationParamsCodec: const StandardMessageCodec(),                /// 传给插件的初始参数的编码方式
        onPlatformViewCreated: _onPlatformViewCreated,                    /// 需要嵌入的 view 创建后触发的事件
      );
    }

    return const MyText("不支持当前环境");
  }

  /// 对于 android 来说,这个 id 是插件中 PlatformViewFactory 的 create() 中生成的 viewId
  /// 对于 ios 来说,这个 id 是插件中 FlutterPlatformViewFactory 的 create() 中生成的 viewId
  void _onPlatformViewCreated(int id) {
    var methodChannel = MethodChannel('com.webabcd.flutter/channel2_view$id');
    widget.controller.setMethodChannel(methodChannel);
  }
}

/// 用于控制 android/ios 和 flutter 通信的 controller
class _MyViewController extends ChangeNotifier {

  late MethodChannel _methodChannel;

  String nativeToFlutterMessage = "";

  /// 接收从 android/ios 发送到 flutter 的数据
  void setMethodChannel(MethodChannel methodChannel) {
    _methodChannel = methodChannel;
    _methodChannel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'nativeToFlutter':
          final result = call.arguments as String;
          nativeToFlutterMessage = result;
          notifyListeners();
          break;
      }
    });
  }

  /// 从 flutter 发送数据到 android/ios
  Future<void> flutterToNative(String message) async {
    await _methodChannel.invokeMethod('flutterToNative', message);
  }
}

ios\Runner\AppDelegate.swift

/*
 * 本例用于演示 ios 插件的开发
 */

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate
{
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
        // 用于为某个插件提供服务
        let registrar1: FlutterPluginRegistrar = self.registrar(forPlugin: "com.webabcd.flutter/plugin1")!
        let registrar2: FlutterPluginRegistrar = self.registrar(forPlugin: "com.webabcd.flutter/plugin2")!
        
        // 注册自定义插件,用于演示 flutter 与 ios 原生之间的数据通信
        MyFlutterPlugin1.register(with: registrar1)
        
        // 注册自定义插件,用于演示 flutter 使用 ios 原生控件,并做数据通信
        MyFlutterPlugin2.register(with: registrar2)
        
        GeneratedPluginRegistrant.register(with: self)
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

ios\Runner\MyFlutterPlugin2.swift

/*
 * 自定义插件,用于演示 flutter 使用 ios 原生控件,并做数据通信
 */

import UIKit
import Flutter

// 自定义插件
class MyFlutterPlugin2: NSObject, FlutterPlugin
{
    static func register(with registrar: FlutterPluginRegistrar)
    {
        let binaryMessenger = registrar.messenger() // binaryMessenger 用于后续通过 FlutterMethodChannel 传输二进制数据
        
        let factory = MyFlutterPlatformViewFactory(binaryMessenger: binaryMessenger)
        registrar.register(factory, withId: "com.webabcd.flutter/myview") // 指定 view 的标识,在 flutter 中通过此标识使用这个 view
    }
}

// 自定义 FlutterPlatformViewFactory 用于创建一个 FlutterPlatformView
class MyFlutterPlatformViewFactory: NSObject,FlutterPlatformViewFactory {
    
    var binaryMessenger: FlutterBinaryMessenger?
    
    init(binaryMessenger: FlutterBinaryMessenger)
    {
        super.init()
        
        self.binaryMessenger = binaryMessenger
    }
    
    // viewId - 创建的 view 实例的 id(当这个 view 创建成功后,回调 UiKitView 的 onPlatformViewCreated 时,会把这个 viewId 传递过去)
    // args - 在 flutter 中通过 UiKitView 的 creationParams 传递过来的初始参数
    func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView
    {
        return MyFlutterPlatformView(frame, viewId: viewId, args: args, binaryMessenger: self.binaryMessenger!)
    }
    
    // 初始参数的编码方式,要与 UiKitView 的 creationParamsCodec 一致
    func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol
    {
        return FlutterStandardMessageCodec.sharedInstance()
    }
}

// 自定义 FlutterPlatformView 用于将指定的 ios 中的 view 嵌入到 flutter 中
class MyFlutterPlatformView: NSObject, FlutterPlatformView {
    
    // 需要嵌入到 flutter 中的 ios 的 view
    var _myView: MyView?
    // 用于 flutter 与 ios 之间的通信
    var _methodChannel: FlutterMethodChannel?
    
    init(_ frame: CGRect, viewId: Int64, args :Any?, binaryMessenger: FlutterBinaryMessenger)
    {
        super.init()
        
        _myView = MyView()
        _myView!.frame = frame
        
        // 获取在 flutter 中通过 UiKitView 的 creationParams 传递过来的初始参数
        if let dict = args as? NSDictionary
        {
            _myView!.showMessage(message: "flutter 创建 UiKitView 时的初始参数 k1:\(dict.value(forKey: "k1") as! String), k2:\(dict.value(forKey: "k2") as! String)")
        }

        // 创建一个 FlutterMethodChannel 并指定其名称,它用于 flutter 和 ios 插件之间的通信(在 flutter 中通过名称获取此 channel 后就可以通信了)
        // binaryMessenger 的意思是这个 FlutterMethodChannel 用于传输二进制数据
        _methodChannel = FlutterMethodChannel(name: "com.webabcd.flutter/channel2_view\(viewId)", binaryMessenger: binaryMessenger)
        // flutter 调用 ios 插件中的方法时,会执行到这里(更详细的说明请参见 MyFlutterPlugin1.swift)
        _methodChannel!.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
          
            let method = call.method
            
            if (method == "flutterToNative")
            {
                let message = call.arguments as! String
                self._myView!.showMessage(message: "flutter to ios: \(message)")
                result(true)
            }
        }
        
        _myView!.setIosToFlutterHandler { message in
            // 通过 FlutterMethodChannel 从 ios 发送数据到 flutter
            self._methodChannel!.invokeMethod("nativeToFlutter", arguments: message)
        }
    }
    
    // 返回需要嵌入到 flutter 中的 ios 的 view
    func view() -> UIView {
        return _myView!
    }
}

ios\Runner\MyView.swift

/*
 * 本例的 view 用于显示在 flutter 中
 */

import Foundation

class MyView : UIView
{
    var textViewBottom = UITextView()
    var textView = UITextView()
    var button = UIButton(type: .custom)
    
    required init?(coder: NSCoder)
    {
        super.init(coder:coder);
    }

    override init(frame: CGRect)
    {
        super.init(frame: frame);
        
        self.textView.font = UIFont.systemFont(ofSize: 14)
        self.textView.textColor = .black
        self.textView.backgroundColor = .clear
        self.textView.textAlignment = .center
        self.textView.isEditable = false
        self.addSubview(self.textView)
        
        self.button.setTitle("发送数据给 flutter", for: .normal)
        self.button.backgroundColor = .blue
        self.button.layer.cornerRadius = 10
        self.button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        self.button.titleLabel?.textColor = .white
        self.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        self.addSubview(self.button)
        
        self.textViewBottom.font = UIFont.boldSystemFont(ofSize: 24)
        self.textViewBottom.textColor = .black
        self.textViewBottom.backgroundColor = .clear
        self.textViewBottom.textAlignment = .center
        self.textViewBottom.isEditable = false
        self.textViewBottom.text = "iOS - View"
        self.addSubview(self.textViewBottom)
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        self.button.frame = CGRect(x: (self.bounds.width - 200) / 2, y: self.bounds.height / 2, width: 200, height: 30)
        self.textView.frame = CGRect(x: 0, y: self.bounds.height / 4, width: self.bounds.width, height: 30)
        self.textViewBottom.frame = CGRect(x: 0, y: self.bounds.height - 60, width: self.bounds.width, height: 40)
    }
    
    // 用于显示 flutter 发送到 ios 的数据
    func showMessage(message: String)
    {
        self.textView.text = message
    }
    
    @objc func buttonPressed()
    {
        // 用于从 ios 发送数据到 flutter
        self.iosToFlutter("\(Int(Date().timeIntervalSince1970 * 1000))")
    }
    
    private var iosToFlutter:(_ message: String) -> () = { p in }
    func setIosToFlutterHandler(iosToFlutter: @escaping ((_ message: String) -> ()))
    {
        self.iosToFlutter = iosToFlutter
    }
}

源码 https://github.com/webabcd/flutter_demo
作者 webabcd

posted @ 2023-04-10 09:15  webabcd  阅读(640)  评论(0编辑  收藏  举报