Sub topic 2
How a view type connects Dart to native code
This chapter explains the mechanism that links a Flutter widget to a native view. It covers the view type string, the factory, the registry, and the order in which they run. It assumes you know basic Flutter and Dart, have used MethodChannel at a basic level, and can read simple Kotlin and Swift. Later chapters build the Android and iOS views in full. Here you only need the model that holds them together.
The problem the view type solves
Flutter draws its own pixels. It does not create TextView or UILabel objects for its widgets. When you want a real native view inside a Flutter screen, Dart code has to ask the native side for one, and the two sides share no objects. They can only exchange messages that cross the engine boundary.
A platform view solves this with a name. Dart says "give me a view of type X", and native code looks up X in a table of registered builders. The name is the view type, a plain string. It is the only thing the two sides must agree on before any view exists.
The three pieces
Three pieces cooperate, and each lives in a different place.
| Piece | Lives in | Job |
|---|---|---|
| View type | Dart and native (same string) | Identifies which native view to build |
| Factory | Native (Kotlin or Swift) | Builds a native view from an id and creation parameters |
| Registry | Native, inside the Flutter engine | Maps view type strings to factories |
The view type is a string such as com.example.app/native_label. By convention it is a reverse-domain prefix, a slash, and a short name. This avoids clashes when several plugins register views in one app.
The factory is a native class. On Android it extends PlatformViewFactory. On iOS it conforms to FlutterPlatformViewFactory. Its create method receives a view id and the creation parameters, and returns a native object that wraps the view.
The registry is owned by the engine. You register a factory once, under a view type. When Dart later asks for that type, the engine finds the factory and calls it.
The wrapper object
The factory does not return a raw View or UIView. It returns a wrapper that Flutter can manage.
- On Android the wrapper implements
PlatformView, which hasgetView()anddispose(). - On iOS the wrapper conforms to
FlutterPlatformView, which has aview()method.
The wrapper gives Flutter a stable handle. The engine asks it for the real view when it needs to attach it, and on Android it calls dispose() when the view is no longer needed. Lifecycle details come in a later chapter. For now, remember that the factory produces a wrapper, and the wrapper holds the view.
The flow from widget to native view
Follow one view from the first build to the screen.
- At app startup, native code registers a factory under the view type string.
- Dart builds an
AndroidVieworUiKitViewwidget with the same view type and optional creation parameters. - When the widget is inserted into the tree, Flutter sends a creation request to the engine through the platform views channel. The request includes a new integer view id, the view type, the layout direction, and the encoded creation parameters.
- The engine looks up the view type in the registry and calls the matching factory.
- The factory builds the wrapper and the native view.
- The engine attaches the native view to the screen at the position and size of the Flutter widget.
- Dart receives a callback,
onPlatformViewCreated, with the view id.
The view id from step 3 is an integer chosen by Flutter. It is unique per view instance, not per view type. Two NativeLabel widgets share a view type but get different ids. The id is what later lets you address one specific native view, for example with a per-view MethodChannel.
Registering on Android
On Android you register through the engine's platform views registry. The registration call takes the view type string and a factory instance.
import android.content.Context
import android.view.View
import android.widget.TextView
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
class NativeLabel(context: Context, text: String) : PlatformView {
private val textView = TextView(context).apply {
this.text = text
textSize = 20f
}
override fun getView(): View = textView
override fun dispose() {}
}
class NativeLabelFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val params = args as? Map<*, *>
val text = params?.get("text") as? String ?: ""
return NativeLabel(context, text)
}
}
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine
.platformViewsController
.registry
.registerViewFactory("com.example.app/native_label", NativeLabelFactory())
}
}Three details in this code carry the model.
PlatformViewFactory(StandardMessageCodec.INSTANCE)tells the engine how to decode the creation parameters. The codec must match the one Dart used to encode them.createreceivesviewId, the same integer Dart later sees inonPlatformViewCreated.registerViewFactoryis where the string and the factory become linked. This line runs inconfigureFlutterEngine, which Flutter calls before the first frame.
Registering on iOS
On iOS the factory and wrapper follow the same shape, but registration goes through a plugin registrar.
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()
}
}
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
}
}
// In AppDelegate.application(_:didFinishLaunchingWithOptions:), after
// GeneratedPluginRegistrant.register(with: self):
//
// let registrar = self.registrar(forPlugin: "NativeLabelPlugin")!
// registrar.register(NativeLabelFactory(), withId: "com.example.app/native_label")The codec is declared in createArgsCodec() instead of the factory's constructor, but its role is the same. The registrar.register(_:withId:) call is the iOS counterpart of registerViewFactory. The string passed as withId is the view type.
The Dart side
The Dart widget names the same view type. Because there is one Dart codebase and two native platforms, a small widget chooses AndroidView or UiKitView by platform.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeLabel extends StatelessWidget {
const NativeLabel({super.key, required this.text});
final String text;
static const String viewType = 'com.example.app/native_label';
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': text};
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
case TargetPlatform.iOS:
return UiKitView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
default:
return const Text('Native view is not supported on this platform');
}
}
}The string 'com.example.app/native_label' now appears in three files: Dart, Kotlin and Swift. Keep it in a single Dart constant, as viewType does here, so that at least the Dart side has one source of truth.
What the codec does
Creation parameters are not passed as live objects. Dart encodes them to bytes with creationParamsCodec, the engine hands the bytes across, and the native side decodes them with its codec.
StandardMessageCodec supports null, booleans, numbers, strings, byte arrays, lists and maps. On the native side these arrive as Map<*, *> in Kotlin and [String: Any] in Swift, which is why both factories cast args before reading "text".
If you pass creationParams but omit creationParamsCodec, Dart throws an assertion error in debug builds, because it cannot encode the value. Passing a custom class that the codec does not support fails at encoding time.
Common errors
Most first-time failures come from a mismatch between the three pieces.
- Different strings. A typo or case difference between Dart and native gives a failure when the view is created. On Android the error mentions an unregistered view type. On iOS the view is typically missing or the engine logs an error. Compare the strings character by character.
- Registering too late. The factory must be registered before Dart builds the widget. On Android, do it in
configureFlutterEngine. On iOS, do it during launch, afterGeneratedPluginRegistrant.register(with: self). - Mismatched codecs. If Dart uses
StandardMessageCodecand the native factory expects a different codec, the parameters decode wrongly or throw. - Unsafe casts.
argsis an untyped value. Cast withas?and supply a default, as the examples do, so a missing key does not crash the native side. - Wrong platform branch.
AndroidViewon iOS, or the reverse, fails because no factory exists for that platform. Select bydefaultTargetPlatform, as shown. - Registering once per engine. Each
FlutterEnginehas its own registry. If your app runs more than one engine, register the factory on each.
Why one registry entry serves many views
Registration happens once, but the factory's create method runs once per widget instance. Ten NativeLabel widgets on screen produce ten calls to create, with ten different view ids and possibly ten different parameter maps. The factory is therefore a template, and it should hold no per-view state itself. Keep per-view state in the wrapper object that create returns.
Exercise
Your Dart widget uses the view type 'com.example.app/native_chart'. The Android app registers its factory under 'com.example.app/nativeChart'. What happens on Android, and where do you fix it? Also, if three of these widgets are on screen, how many times does the factory's create method run and how do the instances differ?
Show answer
Creation fails at runtime on Android because the registry has no entry for the Dart string. The strings must match exactly, so change one side so both read 'com.example.app/native_chart'. Keeping the string in one Dart constant helps on the Dart side. The factory's create method runs three times, once per widget instance. Each call gets a different integer view id, and may get different creation parameters.