Sub topic 1
When Flutter Needs a Native View
Prerequisites
This chapter assumes you know Flutter widgets and Dart, including StatelessWidget. You should have used a MethodChannel once, read simple Kotlin, and be able to run an app on an Android emulator.
When Flutter needs a native view
Flutter draws every pixel itself, so most features need no native code. A platform view is needed when the feature exists only as a native SDK, such as a vendor's map, a payment sheet, or a video player with platform-specific codecs. Flutter then hosts the real native view inside its widget tree.
Prefer a pure Flutter widget or a maintained package when one exists. Platform views cost more memory and frame time than Flutter widgets.
How a view type connects Dart to native code
A view type is a string, such as com.example.app/native_label. Dart passes it to AndroidView or UiKitView. Each native side registers a factory under the same string. When Flutter builds the widget, it asks the matching factory to create the native view.
Building and registering the Android view
Create a PlatformView that wraps the native widget, and a PlatformViewFactory that builds it. Then register the factory in configureFlutterEngine.
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())
}
}On the Dart side, AndroidView(viewType: 'com.example.app/native_label') requests this view. The text value reaches create through the args map, because the Dart widget sends it as creation parameters.
Exercise
What happens if the view type registered in Kotlin differs from the Dart viewType by one character?
Show answer
Flutter finds no factory under the requested name, so the native view does not appear. The app logs an error at runtime.