Sub topic 4
Building and registering the iOS view
This chapter builds the iOS half of the native label. It assumes you can read basic Swift, you have read the previous chapter on the Android factory, and you can run a Flutter app on an iOS simulator or device. By the end you will have a UILabel that Flutter can create on request from a view type string.
The three pieces on iOS
An iOS platform view needs three things:
- A class that conforms to
FlutterPlatformViewand owns oneUIView. - A class that conforms to
FlutterPlatformViewFactoryand creates instances of the first class. - A registration call that tells the engine which factory answers to which view type string.
These match the Android pieces (PlatformView, PlatformViewFactory, registerViewFactory). The difference is in naming and in who cleans up. Android has an explicit dispose() method. iOS relies on ARC (automatic reference counting) releasing your objects.
How a request reaches your factory
When the Dart UiKitView mounts, Flutter asks the engine to create a native view of a given type. The engine looks up the factory registered under that string, calls its create method, and embeds the returned UIView in the Flutter view hierarchy.
The factory is created once and lives for the lifetime of the app. The NativeLabel object is created once per UiKitView that appears.
The view class
FlutterPlatformView has one required method, view(), which returns the UIView Flutter will embed. The class must also inherit from NSObject, because the protocol is an Objective-C protocol.
import Flutter
import UIKit
class NativeLabel: NSObject, FlutterPlatformView {
private let label: UILabel
init(frame: CGRect, arguments args: Any?) {
label = UILabel(frame: frame)
if let params = args as? [String: Any], let text = params["text"] as? String {
label.text = text
}
label.font = UIFont.systemFont(ofSize: 20)
super.init()
}
func view() -> UIView {
return label
}
}A few details are easy to miss:
- Initialization order. Swift requires every stored property to be set before
super.init(). That is whylabelis assigned first andsuper.init()comes last. view()is called by the engine, not by you. It should return the sameUIVieweach time. Do not create a new view inside it. Creating the view ininitand returning the stored reference is the safe pattern.- The frame is a hint. The
framepassed to the factory often has a zero size. Flutter sets the real size from the layout constraints of the Dart widget. Don't make decisions that depend on the initial frame, and use Auto Layout or let the embedding resize the view.
The factory class
FlutterPlatformViewFactory requires create(withFrame:viewIdentifier:arguments:). It also lets you override createArgsCodec(). You must provide that second method if you pass creation parameters, because it tells the engine how to decode the bytes sent from Dart.
import Flutter
import UIKit
class NativeLabelFactory: NSObject, FlutterPlatformViewFactory {
func create(
withFrame frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?
) -> FlutterPlatformView {
return NativeLabel(frame: frame, arguments: args)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}The arguments value is typed Any?. On the Dart side you pass a Map<String, dynamic> with StandardMessageCodec, and the standard codec on iOS turns it into an NSDictionary. Casting to [String: Any] works because Swift bridges NSDictionary automatically. If you send nothing from Dart, args is nil, so keep the cast optional as shown.
The codec returned by createArgsCodec() must match the creationParamsCodec given to UiKitView in Dart. If Dart uses StandardMessageCodec, return FlutterStandardMessageCodec.sharedInstance(). A mismatch fails at runtime with a decoding error or with garbage in args, not at compile time.
Registering the factory
Registration associates the factory with the view type string. You need a FlutterPluginRegistrar, which you get from the app delegate by calling registrar(forPlugin:). The plugin name is only a unique key. Any string that no other plugin uses will do.
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(),
withId: "com.example.app/native_label"
)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}Older project templates use @UIApplicationMain instead of @main. Either works, so keep whatever your project already has.
Registration must run before Dart tries to build the view. Registering in didFinishLaunchingWithOptions, after GeneratedPluginRegistrant.register(with: self), is the usual place. Newer Flutter templates that create the engine implicitly move plugin registration to a different callback. The registrar(forPlugin:) and register(_:withId:) calls stay the same wherever you put them, so check your template's generated AppDelegate for where registration now happens.
Registering from a plugin
If you ship the view as a plugin, the registrar is handed to you, so you do not call registrar(forPlugin:) yourself. A plugin's Swift class implements register(with:):
import Flutter
public class NativeLabelPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
registrar.register(
NativeLabelFactory(),
withId: "com.example.app/native_label"
)
}
}This is how packages such as map or web view plugins expose their views. The final chapter returns to packaging. For now, note that the registration call is the same in an app and in a plugin.
Passing the messenger to the factory
If the native view must talk back to Dart after creation, the factory needs a FlutterBinaryMessenger to build channels. The registrar provides one through registrar.messenger(). You pass it into the factory's initializer:
import Flutter
import UIKit
class MessengerNativeLabelFactory: 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, arguments: args)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}You would register it with registrar.register(MessengerNativeLabelFactory(messenger: registrar.messenger()), withId: "com.example.app/native_label"). This example only stores the messenger. The chapter on per-view channels uses it.
Lifetime and cleanup
The engine holds a reference to each FlutterPlatformView while its UiKitView is in the tree. When the widget is removed, the engine releases the object, and ARC frees it once nothing else retains it. There is no dispose() hook on iOS.
This has one practical consequence. If your view registers observers, timers, or delegate callbacks that retain the view, ARC can never free it. Use weak or unowned references for those callbacks. Remove observers in deinit, which Swift calls when the object is freed.
deinit {
// Remove NotificationCenter observers, invalidate timers, and so on.
}Common errors
| Symptom | Likely cause |
|---|---|
| Red error screen: no registered factory for the view type | The `withId:` string differs from Dart's `viewType`, or registration never ran |
| Build error "class does not implement protocol" | Missing `create(withFrame:viewIdentifier:arguments:)` or `view()`, or the signature differs from the protocol |
| `args` is always `nil` | Dart did not pass `creationParams`, or it passed them without a `creationParamsCodec` |
| Creation parameters arrive garbled | Dart and iOS use different codecs |
| View is blank or zero-sized | The Dart widget has unbounded constraints, for example no `SizedBox` around it in a `Column` |
| View never freed after leaving the screen | A retain cycle from a closure, timer, or delegate |
| Crash casting `args` | `args` is not a `[String: Any]`, for instance when Dart sent a `List` or a `String` |
Checking the result
Run the app on a simulator with the Dart NativeLabel widget from the previous chapter on screen. You should see the text you passed from Dart rendered in a 20-point system font. Rendering the label on Android and on iOS from one Dart widget confirms that both factories use the same view type string and the same creation parameters.
To test the connection with no Dart changes, change the font size in NativeLabel and hot restart. Hot reload does not re-run native code. Swift changes need a full rebuild with flutter run.
Exercise
Your iOS app shows the error "no registered factory for view type com.example.app/native_label" even though NativeLabelFactory exists. Give two possible causes and say how you would check each one.
Show answer
First, the string passed to register(_:withId:) may differ from the viewType in Dart. Compare the two strings character by character, including case and the package prefix. Second, registration may never run, or may run after the widget builds. Confirm that the registrar(forPlugin:) and register calls are in the AppDelegate path your project actually uses, and put a print or breakpoint on the register call to see that it executes at launch. A third cause is that the Swift file is not part of the Runner target, so check its target membership in Xcode.
Exercise
Why must NativeLabel's initializer assign the label property before calling super.init(), and why does NativeLabel inherit from NSObject?
Show answer
Swift requires every stored property to be initialized before super.init() runs, so label must be assigned first. NativeLabel inherits from NSObject because FlutterPlatformView is an Objective-C protocol, and conforming classes must be NSObject subclasses.