Sub topic 3
Building and registering the Android view
This chapter covers the Android half of a platform view. It assumes you can read basic Kotlin, you know what a MethodChannel is, and you have an Android emulator or device that runs a Flutter app. The previous chapter explained how a view type string links Dart to native code. Here you write the two Kotlin classes that sit behind that string and register them with the engine.
What you build on the Android side
An Android platform view needs three pieces:
- A class that implements
PlatformView. It wraps one nativeViewand says when that view is no longer needed. - A class that extends
PlatformViewFactory. Flutter calls it each time a DartAndroidViewasks for a new instance. - A registration call that links a view type string to the factory.
The Dart widget never creates the native view itself. It sends the view type and the creation parameters to the engine. The engine looks up the factory registered under that string and asks it for a PlatformView.
The PlatformView interface
PlatformView is an interface from io.flutter.plugin.platform. Two methods are required.
getView()returns the nativeViewthat Flutter displays.dispose()is called once, when Flutter removes the view for good. Release anything that would otherwise leak.
Here is a minimal wrapper around a TextView:
import android.content.Context
import android.view.View
import android.widget.TextView
import io.flutter.plugin.platform.PlatformView
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() {}
}Three details matter here.
- Build the view in the constructor. Flutter may call
getView()more than once. Always return the same instance, and do not create a new view insidegetView(). - Use the
Contextyou are given. The factory receives it, so pass it into the view. Do not cast it toActivity. Depending on the composition mode, it can be a wrapper around the real context. - Do not attach the view to a parent yourself. Flutter adds it to its own container. If your view already has a parent when Flutter tries to add it, Android throws an
IllegalStateException.
PlatformView has a few optional methods with default behavior: onFlutterViewAttached, onFlutterViewDetached, onInputConnectionLocked and onInputConnectionUnlocked. You only override them for text input edge cases or when your view needs to know which Flutter view hosts it. Most views never need them.
The PlatformViewFactory
A factory turns a request from Dart into a PlatformView. Extend PlatformViewFactory and pass a codec to its constructor:
import android.content.Context
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
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)
}
}The codec given to the constructor decodes the creation parameters that Dart sent. Dart's creationParamsCodec and this codec must match. The Dart widget in this tutorial uses StandardMessageCodec, so the factory does too. If you use a different codec on one side only, args arrives as garbage or decoding fails.
The create method receives three values:
| Parameter | Meaning |
|---|---|
| `context` | An Android `Context` to build views with. |
| `viewId` | A unique integer for this instance. It is the same id Dart receives in `onPlatformViewCreated`. |
| `args` | The decoded creation parameters, or `null` if Dart sent none. |
Reading arguments defensively
args has type Any?. With StandardMessageCodec, a Dart Map<String, dynamic> arrives as a Kotlin Map<Any?, Any?>. A Dart int arrives as Int or Long, depending on its size. A Dart double arrives as Double.
Use safe casts (as?) and fall back to a default, as the example does. A hard cast such as args as Map<String, Any> crashes the whole app when Dart sends nothing, or sends a different shape.
The next chapters cover creation parameters in more detail. For now, the pattern is: cast safely, supply a default, and build the view.
Registering the factory
Registration links the view type string to the factory. In an app (not a plugin), register inside configureFlutterEngine in your FlutterActivity:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine
.platformViewsController
.registry
.registerViewFactory("com.example.app/native_label", NativeLabelFactory())
}
}The string "com.example.app/native_label" must be identical to the viewType in the Dart widget. Use a reverse-domain prefix so it cannot collide with a view type from another package. Matching is exact and case-sensitive.
Here is the complete Android file for the label example. It combines all three pieces in MainActivity.kt, under android/app/src/main/kotlin/<your package>/:
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())
}
}Add a package line at the top that matches the folder the file lives in. Your project's generated MainActivity.kt already has one.
Registering from a plugin
If the view ships inside a Flutter plugin instead of an app, there is no configureFlutterEngine to edit. The plugin's FlutterPlugin class registers the factory when the engine attaches it:
import io.flutter.embedding.engine.plugins.FlutterPlugin
class NativeLabelPlugin : FlutterPlugin {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
binding.platformViewRegistry.registerViewFactory(
"com.example.app/native_label",
NativeLabelFactory()
)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {}
}The factory and view classes stay the same. Only the place of registration changes. The last chapter of this tutorial covers plugin packaging.
Disposal on the Android side
Flutter calls dispose() when the Dart widget leaves the tree and the platform view is destroyed. After that, Flutter does not touch the view again. Your job is to stop anything that could keep running or keep the view alive.
Typical things to release:
- Handler callbacks and timers.
- Listeners registered on system services, such as sensors or connectivity.
- Native SDK objects, such as a map or video player, that hold their own resources.
- Channel handlers for this view (covered in a later chapter).
This example shows a view that updates itself every second and stops when it is disposed:
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.TextView
import io.flutter.plugin.platform.PlatformView
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class NativeClock(context: Context) : PlatformView {
private val handler = Handler(Looper.getMainLooper())
private val textView = TextView(context).apply { textSize = 20f }
private val tick = object : Runnable {
override fun run() {
val format = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
textView.text = format.format(Date())
handler.postDelayed(this, 1000)
}
}
init {
handler.post(tick)
}
override fun getView(): View = textView
override fun dispose() {
handler.removeCallbacks(tick)
}
}Without the removeCallbacks call, the Runnable keeps rescheduling itself. The handler holds the runnable, the runnable holds the TextView, and the TextView holds its context. Every clock the user ever scrolled past would stay in memory and keep updating.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Dart shows an error such as "Unregistered view type" or the view area stays blank | The view type strings differ, or the factory was never registered | Compare the strings character by character. Confirm `registerViewFactory` runs, and that `super.configureFlutterEngine(flutterEngine)` is still called. |
| `args` is `null` in `create` | Dart omitted `creationParams` | Provide a default. This is normal when the widget passes no parameters. |
| Cast or decode exception in `create` | The codecs on the two sides differ, or the argument shape changed | Use `StandardMessageCodec` on both sides. Use safe casts. |
| `IllegalStateException: The specified child already has a parent` | `getView()` returns a view that is already attached, or builds a new view each call in a way that reuses a parent | Create the view once in the constructor. Never add it to a layout yourself. |
| Memory grows as the user scrolls through a list of native views | `dispose()` does not release callbacks or listeners | Remove handlers, listeners and SDK references in `dispose()`. |
| The same factory is registered twice and the app logs a warning or throws | Registration code runs in two places, such as app and plugin | Register each view type once. Give separate views separate type strings. |
Checking your work
The Android side is correct when these hold:
- The view type string in Kotlin matches the Dart
viewTypeexactly. - The factory's codec matches the Dart
creationParamsCodec. createtoleratesnullor incomplete arguments.getView()returns one stable instance, created in the constructor.dispose()stops everything the view started.
To test, run the app on an Android emulator with the NativeLabel Dart widget from the previous chapter. Pass different strings and confirm they appear. Then navigate away and back to confirm that a new instance is created each time.
Exercise
A teammate's PlatformViewFactory crashes the app when the Dart widget is used without creationParams. The factory contains val text = (args as Map<String, Any>)["text"] as String. Rewrite that line so the factory returns an empty label instead of crashing, and explain why the original crashes.
Show answer
Use safe casts and a default: val text = (args as? Map<*, *>)?.get("text") as? String ?: "". The original crashes because when Dart sends no creation parameters, args is null. The hard cast null as Map<String, Any> throws a NullPointerException or TypeCastException. The safe version evaluates to null at the first as?, skips the lookup, and falls back to the empty string.
Exercise
Your PlatformView starts a Handler that posts a repeating Runnable which updates a TextView. Users report that the app slows down after they open and close the screen many times. What is the cause, and which method do you change?
Show answer
The Runnable is never stopped. Each time the screen closes, the platform view is destroyed, but the handler still holds the Runnable, which reschedules itself and holds the TextView. The views stay in memory and keep running. Change dispose() to call handler.removeCallbacks(tick) (the repeating Runnable) so the work stops when the view is destroyed.