Sub topic 2
Embedding Native Android and iOS Views in Flutter: Building and Registering the iOS View
This chapter assumes you know Flutter widgets and MethodChannel, can read Swift, and have an iOS target that builds in Xcode. The Android side is covered elsewhere, so the examples here focus on iOS, with the Dart widget showing both platforms.
Building the iOS view
A platform view is a native view that Flutter draws inside its widget tree. On iOS, you write two Swift classes. A factory (FlutterPlatformViewFactory) creates the view. The view (FlutterPlatformView) wraps a UILabel. The factory also receives the messenger, which you need later for per-view messaging.
import Flutter
import UIKit
class NativeLabelFactory: NSObject, FlutterPlatformViewFactory {
private let messenger: FlutterBinaryMessenger
init(messenger: FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
return NativeLabel(frame: frame, viewId: viewId, arguments: args, messenger: messenger)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
class NativeLabel: NSObject, FlutterPlatformView {
private let label: UIView
private let channel: FlutterMethodChannel
init(frame: CGRect, viewId: Int64, arguments args: Any?, messenger: FlutterBinaryMessenger) {
let lbl = UILabel(frame: frame)
lbl.font = UIFont.systemFont(ofSize: 20)
if let params = args as? [String: Any], let text = params["text"] as? String {
lbl.text = text
}
label = lbl
channel = FlutterMethodChannel(name: "com.example.app/native_label/\(viewId)", binaryMessenger: messenger)
super.init()
channel.setMethodCallHandler { [weak lbl] call, result in
if call.method == "setText", let text = call.arguments as? String {
lbl?.text = text
result(nil)
} else {
result(FlutterMethodNotImplemented)
}
}
}
func view() -> UIView {
return label
}
}Registering the factory
Register the factory with the same view type string that Dart uses. Do this in AppDelegate.
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let registrar = self.registrar(forPlugin: "NativeLabelPlugin")!
registrar.register(
NativeLabelFactory(messenger: registrar.messenger()),
withId: "com.example.app/native_label"
)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}Showing the view and passing creation parameters
Choose the widget by platform. Pass initial data as creationParams, encoded with the same codec the factory returns from createArgsCodec.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeLabel extends StatefulWidget {
const NativeLabel({super.key});
@override
State<NativeLabel> createState() => _NativeLabelState();
}
class _NativeLabelState extends State<NativeLabel> {
static const String viewType = 'com.example.app/native_label';
MethodChannel? _channel;
void _onPlatformViewCreated(int id) {
_channel = MethodChannel('$viewType/$id');
}
Future<void> _rename() async {
await _channel?.invokeMethod<void>('setText', 'Updated from Dart');
}
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': 'Hello from Dart'};
final Widget nativeView;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
nativeView = AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
onPlatformViewCreated: _onPlatformViewCreated,
);
case TargetPlatform.iOS:
nativeView = UiKitView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
onPlatformViewCreated: _onPlatformViewCreated,
);
default:
nativeView = const Text('Native view is not supported on this platform');
}
return Column(
children: [
SizedBox(height: 200, child: nativeView),
ElevatedButton(onPressed: _rename, child: const Text('Rename')),
],
);
}
}Exercise
The Swift factory is registered as "com.example.app/nativelabel", but the Dart widget uses "com.example.app/nativelabel/" with the view id appended for messaging. Why must the registered view type match the Dart viewType exactly, and what happens if it does not?
Show answer
Flutter looks up the factory by that string when Dart asks for a view. If the strings differ, no factory matches, and the view does not appear. Flutter throws an error on the Dart side. The per-view channel name is different: it is built from the view type plus the numeric id, so it only has to match between the Swift channel and the Dart MethodChannel.