Sub topic 7
Talking to a native view after it is created
This chapter assumes you can read basic Kotlin and Swift. It also assumes you know how a MethodChannel works and have a platform view showing on screen from the earlier chapters. Creation parameters set a native view's starting state, and after that they are no use. To change the view later, read its state, or react to what the user does inside it, you need a channel for that one view instance.
Why creation parameters are not enough
Creation parameters are read once, when the factory builds the view. A text label can live with that. A map, a video player, or a counter cannot. You need to say "move the camera", "pause", or "reset", and the native side needs to say "the user tapped a marker".
The standard solution is one MethodChannel per view instance. A single global channel is a poor fit for two reasons. A screen can host several instances of the same view type, and a global channel would need an id in every call to tell them apart. A per-view channel also gives you a natural cleanup point when the view goes away.
The per-view channel pattern
Both sides have to agree on a channel name that includes the view id. The id is an integer that Flutter assigns to each platform view instance. It reaches Dart in the onPlatformViewCreated callback. It reaches native code as the viewId argument of the factory's create method.
A common naming scheme is the view type string, a slash, and the id:
- Dart:
MethodChannel('com.example.app/native_counter/$id') - Native: the same string, built from the
viewIdthe factory receives.
The native side needs a BinaryMessenger, the object a channel uses to send and receive messages. The factory does not receive one in create, so you pass it into the factory's constructor when you register it.
The order in the diagram matters. The native view opens its channel inside the factory call, so its handler already exists when onPlatformViewCreated fires in Dart. A Dart call made from that callback onward therefore finds a listener. The reverse is not guaranteed. If native code sends a message before Dart has set its handler, nobody receives it. Set the Dart handler as the first thing you do in onPlatformViewCreated.
The Android side
The sample view is a Button that counts taps. It implements MethodCallHandler, so the same class owns the view, the channel, and the state.
import android.content.Context
import android.view.View
import android.widget.Button
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
const val COUNTER_VIEW_TYPE = "com.example.app/native_counter"
class NativeCounter(
context: Context,
messenger: BinaryMessenger,
viewId: Int
) : PlatformView, MethodChannel.MethodCallHandler {
private var count = 0
private var step = 1
private val button = Button(context)
private val channel = MethodChannel(messenger, "$COUNTER_VIEW_TYPE/$viewId")
init {
render()
button.setOnClickListener {
count += step
render()
channel.invokeMethod("countChanged", count)
}
channel.setMethodCallHandler(this)
}
private fun render() {
button.text = "Count: $count"
}
override fun getView(): View = button
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"reset" -> {
count = 0
render()
result.success(count)
}
"setStep" -> {
val newStep = call.argument<Int>("step")
if (newStep == null || newStep < 1) {
result.error("bad_args", "step must be a positive integer", null)
} else {
step = newStep
result.success(null)
}
}
else -> result.notImplemented()
}
}
override fun dispose() {
channel.setMethodCallHandler(null)
}
}
class NativeCounterFactory(
private val messenger: BinaryMessenger
) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
return NativeCounter(context, messenger, viewId)
}
}
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine
.platformViewsController
.registry
.registerViewFactory(
COUNTER_VIEW_TYPE,
NativeCounterFactory(flutterEngine.dartExecutor.binaryMessenger)
)
}
}Three details are easy to miss:
- Every branch of
onMethodCallmust call exactly one ofsuccess,error, ornotImplemented. If none is called, the DartFuturenever completes. channel.invokeMethodruns inside the click listener, which is on the main thread. Platform channel calls must be made from the main thread.dispose()clears the handler so the channel no longer holds a reference to the view.
The iOS side
The Swift version has the same structure. FlutterPlatformView has no dispose method, so cleanup goes in deinit.
import Flutter
import UIKit
let counterViewType = "com.example.app/native_counter"
class NativeCounterFactory: 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 NativeCounter(frame: frame, viewId: viewId, messenger: messenger)
}
}
class NativeCounter: NSObject, FlutterPlatformView {
private let button = UIButton(type: .system)
private let channel: FlutterMethodChannel
private var count = 0
private var step = 1
init(frame: CGRect, viewId: Int64, messenger: FlutterBinaryMessenger) {
channel = FlutterMethodChannel(
name: "\(counterViewType)/\(viewId)",
binaryMessenger: messenger
)
button.frame = frame
super.init()
render()
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
channel.setMethodCallHandler { [weak self] call, result in
guard let self = self else {
result(FlutterMethodNotImplemented)
return
}
self.handle(call, result: result)
}
}
deinit {
channel.setMethodCallHandler(nil)
}
func view() -> UIView {
return button
}
private func render() {
button.setTitle("Count: \(count)", for: .normal)
}
@objc private func tapped() {
count += step
render()
channel.invokeMethod("countChanged", arguments: count)
}
private func handle(_ call: FlutterMethodCall, result: FlutterResult) {
switch call.method {
case "reset":
count = 0
render()
result(count)
case "setStep":
let args = call.arguments as? [String: Any]
if let newStep = args?["step"] as? Int, newStep >= 1 {
step = newStep
result(nil)
} else {
result(FlutterError(
code: "bad_args",
message: "step must be a positive integer",
details: nil
))
}
default:
result(FlutterMethodNotImplemented)
}
}
}
// In AppDelegate.application(_:didFinishLaunchingWithOptions:), after
// GeneratedPluginRegistrant.register(with: self):
//
// let registrar = self.registrar(forPlugin: "NativeCounterPlugin")!
// registrar.register(
// NativeCounterFactory(messenger: registrar.messenger()),
// withId: counterViewType
// )The [weak self] capture is deliberate. The channel stores the handler closure, and the view stores the channel. A strong capture would create a retain cycle, deinit would never run, and the view would leak.
The Dart side: a small controller
Scattering MethodChannel calls through widget code makes them hard to find and test. A controller class wraps the channel and exposes typed methods. It also handles calls coming from native.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeCounterController {
NativeCounterController(int viewId, {this.onCountChanged})
: _channel = MethodChannel('${NativeCounterView.viewType}/$viewId') {
_channel.setMethodCallHandler(_handleCall);
}
final MethodChannel _channel;
final ValueChanged<int>? onCountChanged;
Future<int> reset() async {
final value = await _channel.invokeMethod<int>('reset');
return value ?? 0;
}
Future<void> setStep(int step) {
return _channel.invokeMethod<void>('setStep', <String, dynamic>{'step': step});
}
Future<Object?> _handleCall(MethodCall call) async {
switch (call.method) {
case 'countChanged':
onCountChanged?.call(call.arguments as int);
return null;
default:
throw MissingPluginException('Unknown method ${call.method}');
}
}
void dispose() {
_channel.setMethodCallHandler(null);
}
}
class NativeCounterView extends StatefulWidget {
const NativeCounterView({super.key});
static const String viewType = 'com.example.app/native_counter';
@override
State<NativeCounterView> createState() => _NativeCounterViewState();
}
class _NativeCounterViewState extends State<NativeCounterView> {
NativeCounterController? _controller;
int _count = 0;
void _onCreated(int id) {
_controller = NativeCounterController(
id,
onCountChanged: (value) {
if (mounted) setState(() => _count = value);
},
);
}
Future<void> _reset() async {
final value = await _controller?.reset();
if (mounted && value != null) setState(() => _count = value);
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Widget nativeView;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
nativeView = AndroidView(
viewType: NativeCounterView.viewType,
onPlatformViewCreated: _onCreated,
);
case TargetPlatform.iOS:
nativeView = UiKitView(
viewType: NativeCounterView.viewType,
onPlatformViewCreated: _onCreated,
);
default:
nativeView = const Text('Native view is not supported on this platform');
}
return Column(
children: [
SizedBox(height: 120, child: nativeView),
Text('Flutter sees: $_count'),
ElevatedButton(onPressed: _reset, child: const Text('Reset from Flutter')),
],
);
}
}The mounted checks guard against a message arriving after the widget has been removed. The _controller? calls handle the short window before onPlatformViewCreated runs, when no controller exists yet.
Data types and codecs
A MethodChannel uses StandardMethodCodec by default, the same family as StandardMessageCodec. It carries null, booleans, numbers, strings, byte and number arrays, lists, and maps. A Dart int arrives as Int or Long in Kotlin, depending on its size, and as NSNumber in Swift. Use call.argument<Int>("step") on Android. On iOS, cast with as? Int. Custom classes are not supported, so convert them to maps before sending.
Errors you will see
| Symptom | Likely cause |
|---|---|
| `MissingPluginException` in Dart | The channel names differ, the native handler is not set yet, or the view was already disposed. |
| A `Future` that never completes | A native branch returned without calling `success`, `error`, or `notImplemented`. |
| `PlatformException(bad_args, ...)` | Native code rejected the arguments. Catch it in Dart and show or log `e.message`. |
| Native-to-Dart message silently lost | Dart had not yet called `setMethodCallHandler`, or you cleared it too early. |
| Crash or odd behavior on a background thread | The channel call was not made from the main thread. |
What this chapter does not cover
Cleanup is only touched on here. The handler is cleared in dispose or deinit, but the full lifecycle and disposal rules are covered in a later chapter. Touch routing between the Flutter and native layers also has its own chapter.
Exercise
In the Kotlin sample, the factory receives a BinaryMessenger through its constructor instead of in create(). Why is the channel name built from viewId, and what breaks if two NativeCounter views are on screen but both use the fixed name "com.example.app/native_counter"?
Show answer
The channel name must be unique per view instance because a channel name identifies one handler on each side. With a fixed name, the second view's setMethodCallHandler replaces the first view's handler. A Dart call such as reset would then reach only the most recently created native view, and the Dart controllers for both widgets would receive each other's countChanged events. Including viewId (the same integer Dart receives in onPlatformViewCreated) gives each pair of controller and native view its own private channel.
Exercise
Add a "getCount" method that returns the current count from the native view without changing it. List the three places you must edit, and say what Dart type the call should request.
Show answer
First, add a "getCount" branch to onMethodCall in Kotlin that calls result.success(count). Second, add a "getCount" case to the handle(:result:) switch in Swift that calls result(count). Third, add a method to NativeCounterController, for example Future<int> getCount() async => (await channel.invokeMethod<int>('getCount')) ?? 0. The call should request int, because the standard codec delivers a native integer as a Dart int.