Sub topic 7
Talking to a Native View After It Is Created
This chapter assumes you know basic Flutter widgets and Dart, can read simple Kotlin and Swift, and understand the basic idea of a MethodChannel. A platform view is already registered on both native platforms. The goal here is to send commands to one particular native view instance after Flutter displays it.
Why the view ID matters
A view type identifies the kind of native view, such as com.example.app/native_counter. Flutter can create several instances of that type. Each instance receives a different integer view ID.
Use that ID in a channel name:
com.example.app/native_counter/12The number 12 identifies one native view, not every counter in the application. This prevents a command sent to one widget from changing another widget.
The communication path looks like this:
Create the channel in Dart
onPlatformViewCreated runs after Flutter has created the platform view. Store a channel for that instance, then invoke methods through it.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeCounter extends StatefulWidget {
const NativeCounter({super.key});
@override
State<NativeCounter> createState() => _NativeCounterState();
}
class _NativeCounterState extends State<NativeCounter> {
static const viewType = 'com.example.app/native_counter';
MethodChannel? _channel;
void _onPlatformViewCreated(int viewId) {
_channel = MethodChannel('$viewType/$viewId');
}
Future<void> _reset() async {
final channel = _channel;
if (channel == null) {
return;
}
try {
await channel.invokeMethod<void>('reset');
} on PlatformException catch (error) {
debugPrint('Native reset failed: ${error.code}');
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
height: 200,
child: AndroidView(
viewType: viewType,
onPlatformViewCreated: _onPlatformViewCreated,
gestureRecognizers: {
Factory<OneSequenceGestureRecognizer>(
EagerGestureRecognizer.new,
),
},
),
),
ElevatedButton(
onPressed: _reset,
child: const Text('Reset'),
),
],
);
}
}In a cross-platform widget, replace AndroidView with UiKitView on iOS. The channel naming rule remains the same. The method name, reset, is also part of the contract and must match native code exactly.
Handle the method on Android
Pass the Flutter binary messenger into the native view. The view can then listen on the channel that contains its viewId.
import android.content.Context
import android.view.View
import android.widget.TextView
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
class NativeCounter(
context: Context,
messenger: io.flutter.plugin.common.BinaryMessenger,
viewId: Int
) : PlatformView {
private val counter = TextView(context)
private val channel = MethodChannel(
messenger,
"com.example.app/native_counter/$viewId"
)
init {
counter.text = "0"
channel.setMethodCallHandler { call, result ->
when (call.method) {
"reset" -> {
counter.text = "0"
result.success(null)
}
else -> result.notImplemented()
}
}
}
override fun getView(): View = counter
override fun dispose() {
channel.setMethodCallHandler(null)
}
}Your PlatformViewFactory supplies the messenger and viewId when it constructs NativeCounter. The factory and Dart code must use the same view type and channel format.
Handle the method on iOS
The iOS view follows the same design. Its factory receives a messenger and passes it to each view instance.
import Flutter
import UIKit
final class NativeCounter: NSObject, FlutterPlatformView {
private let label: UILabel
private let channel: FlutterMethodChannel
init(frame: CGRect, messenger: FlutterBinaryMessenger, viewId: Int64) {
label = UILabel(frame: frame)
channel = FlutterMethodChannel(
name: "com.example.app/native_counter/\(viewId)",
binaryMessenger: messenger
)
super.init()
label.text = "0"
channel.setMethodCallHandler { [weak self] call, result in
guard call.method == "reset" else {
result(FlutterMethodNotImplemented)
return
}
self?.label.text = "0"
result(nil)
}
}
func view() -> UIView {
return label
}
func dispose() {
channel.setMethodCallHandler(nil)
}
}The factory creates this object with the platform view ID supplied by Flutter. Register the factory with the same view type used in Dart.
Handle results and failures
Native code should always complete the method call with success, an error, or “not implemented.” Dart can then distinguish a successful command from a native failure.
Use method arguments when a command needs data:
await _channel?.invokeMethod<void>(
'setValue',
<String, dynamic>{'value': 42},
);On the native side, validate the argument type before changing the view. Do not assume that Dart sent valid data.
A channel is useful for commands and small state changes. It is not a good transport for a high-volume video stream or large images. Those cases need a texture, a dedicated plugin API, or another data path.
Lifecycle and ownership
The native view owns its native resources until Flutter disposes it. Remove method handlers in dispose so a discarded view cannot keep receiving messages. In Dart, avoid invoking methods before onPlatformViewCreated has supplied the channel.
Exercise
Two native counters are visible, but pressing Reset changes both. What is the most likely design error?
Show answer
Both native views are listening on the same fixed channel name. Include each platform view's unique ID in the channel name and create the matching channel in Dart.