使用平台檢視在 Flutter 應用程式中主機原生 iOS 檢視

平台檢視讓您可以在 Flutter 應用程式中嵌入原生檢視,因此您可以從 Dart 對原生檢視套用轉換、剪輯和不透明度。

例如,這讓您可以直接在 Flutter 應用程式中使用 Android 和 iOS SDK 中的原生 Google 地圖。

iOS 僅使用混合式組成,這表示原生 UIView 會附加到檢視層級結構。

若要在 iOS 上建立平台檢視,請使用下列說明

在 Dart 端

在 Dart 端,建立一個 Widget 並新增建置實作,如以下步驟所示。

在 Dart 小工具檔案中,進行類似於 native_view_example.dart 中顯示的變更

  1. 新增下列匯入

    import 'package:flutter/foundation.dart';
    import 'package:flutter/services.dart';
  2. 實作 build() 方法

    Widget build(BuildContext context) {
      // This is used in the platform side to register the view.
      const String viewType = '<platform-view-type>';
      // Pass parameters to the platform side.
      final Map<String, dynamic> creationParams = <String, dynamic>{};
    
      return UiKitView(
        viewType: viewType,
        layoutDirection: TextDirection.ltr,
        creationParams: creationParams,
        creationParamsCodec: const StandardMessageCodec(),
      );
    }

如需更多資訊,請參閱以下 API 文件:UIKitView

在平台端

在平台端,請使用 Swift 或 Objective-C

實作工廠和平台檢視。 FLNativeViewFactory 會建立平台檢視,而平台檢視會提供對 UIView 的參考。例如,FLNativeView.swift

import Flutter
import UIKit

class FLNativeViewFactory: NSObject, FlutterPlatformViewFactory {
    private var messenger: FlutterBinaryMessenger

    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
        super.init()
    }

    func create(
        withFrame frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?
    ) -> FlutterPlatformView {
        return FLNativeView(
            frame: frame,
            viewIdentifier: viewId,
            arguments: args,
            binaryMessenger: messenger)
    }

    /// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`.
    public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
          return FlutterStandardMessageCodec.sharedInstance()
    }
}

class FLNativeView: NSObject, FlutterPlatformView {
    private var _view: UIView

    init(
        frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?,
        binaryMessenger messenger: FlutterBinaryMessenger?
    ) {
        _view = UIView()
        super.init()
        // iOS views can be created here
        createNativeView(view: _view)
    }

    func view() -> UIView {
        return _view
    }

    func createNativeView(view _view: UIView){
        _view.backgroundColor = UIColor.blue
        let nativeLabel = UILabel()
        nativeLabel.text = "Native text from iOS"
        nativeLabel.textColor = UIColor.white
        nativeLabel.textAlignment = .center
        nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)
        _view.addSubview(nativeLabel)
    }
}

最後,註冊平台檢視。這可以在應用程式或外掛程式中完成。

對於應用程式註冊,請修改應用程式的 AppDelegate.swift

import Flutter
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)

        weak var registrar = self.registrar(forPlugin: "plugin-name")

        let factory = FLNativeViewFactory(messenger: registrar!.messenger())
        self.registrar(forPlugin: "<plugin-name>")!.register(
            factory,
            withId: "<platform-view-type>")
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

對於外掛程式註冊,請修改外掛程式的檔案 (例如,FLPlugin.swift)

import Flutter
import UIKit

class FLPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let factory = FLNativeViewFactory(messenger: registrar.messenger())
        registrar.register(factory, withId: "<platform-view-type>")
    }
}

在 Objective-C 中,新增工廠和平台檢視的標頭。例如,如 FLNativeView.h 中所示

#import <Flutter/Flutter.h>

@interface FLNativeViewFactory : NSObject <FlutterPlatformViewFactory>
- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
@end

@interface FLNativeView : NSObject <FlutterPlatformView>

- (instancetype)initWithFrame:(CGRect)frame
               viewIdentifier:(int64_t)viewId
                    arguments:(id _Nullable)args
              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;

- (UIView*)view;
@end

實作工廠和平台檢視。 FLNativeViewFactory 會建立平台檢視,而平台檢視會提供對 UIView 的參考。例如,FLNativeView.m

#import "FLNativeView.h"

@implementation FLNativeViewFactory {
  NSObject<FlutterBinaryMessenger>* _messenger;
}

- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
  self = [super init];
  if (self) {
    _messenger = messenger;
  }
  return self;
}

- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
                                   viewIdentifier:(int64_t)viewId
                                        arguments:(id _Nullable)args {
  return [[FLNativeView alloc] initWithFrame:frame
                              viewIdentifier:viewId
                                   arguments:args
                             binaryMessenger:_messenger];
}

/// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`.
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
    return [FlutterStandardMessageCodec sharedInstance];
}

@end

@implementation FLNativeView {
   UIView *_view;
}

- (instancetype)initWithFrame:(CGRect)frame
               viewIdentifier:(int64_t)viewId
                    arguments:(id _Nullable)args
              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
  if (self = [super init]) {
    _view = [[UIView alloc] init];
  }
  return self;
}

- (UIView*)view {
  return _view;
}

@end

最後,註冊平台檢視。這可以在應用程式或外掛程式中完成。

對於應用程式註冊,請修改應用程式的 AppDelegate.m

#import "AppDelegate.h"
#import "FLNativeView.h"
#import "GeneratedPluginRegistrant.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];

   NSObject<FlutterPluginRegistrar>* registrar =
      [self registrarForPlugin:@"plugin-name"];

  FLNativeViewFactory* factory =
      [[FLNativeViewFactory alloc] initWithMessenger:registrar.messenger];

  [[self registrarForPlugin:@"<plugin-name>"] registerViewFactory:factory
                                                          withId:@"<platform-view-type>"];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

對於外掛註冊,修改主要外掛檔案(例如,FLPlugin.m

#import <Flutter/Flutter.h>
#import "FLNativeView.h"

@interface FLPlugin : NSObject<FlutterPlugin>
@end

@implementation FLPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FLNativeViewFactory* factory =
      [[FLNativeViewFactory alloc] initWithMessenger:registrar.messenger];
  [registrar registerViewFactory:factory withId:@"<platform-view-type>"];
}

@end

更多資訊,請參閱 API 文件,如下所示:

組合

在 Dart 中實作 build() 方法時,您可以使用 defaultTargetPlatform 來偵測平台,並決定要使用哪個小工具

Widget build(BuildContext context) {
  // This is used in the platform side to register the view.
  const String viewType = '<platform-view-type>';
  // Pass parameters to the platform side.
  final Map<String, dynamic> creationParams = <String, dynamic>{};

  switch (defaultTargetPlatform) {
    case TargetPlatform.android:
    // return widget on Android.
    case TargetPlatform.iOS:
    // return widget on iOS.
    default:
      throw UnsupportedError('Unsupported platform view');
  }
}

效能

Flutter 中的平台檢視會產生效能折衷。

例如,在典型的 Flutter 應用程式中,Flutter UI 會在專用的光柵執行緒上組成。這讓 Flutter 應用程式可以快速執行,因為主平台執行緒很少會被封鎖。

當平台檢視使用混合組成來呈現時,Flutter UI 會從平台執行緒組成。平台執行緒會與其他任務競爭,例如處理作業系統或外掛訊息。

當 iOS PlatformView 在螢幕上時,螢幕更新率會限制在 80fps,以避免呈現抖動。

對於複雜的情況,有一些技術可以用來減輕效能問題。

例如,您可以在 Dart 中執行動畫時使用暫存區紋理。換句話說,如果在呈現平台檢視時動畫很慢,請考慮擷取原生檢視的螢幕擷取畫面,並將其呈現為紋理。

組成限制

在組成 iOS Platform Views 時有一些限制。