Sub topic 12
Alternatives to platform views and shipping as a plugin
This chapter assumes you can already build a platform view on both platforms. That means a PlatformViewFactory on Android, a FlutterPlatformViewFactory on iOS, and AndroidView and UiKitView in Dart. It also assumes you know the basics of MethodChannel and have seen the composition and performance costs from the previous chapters.
A platform view is the most general way to show native UI in Flutter, and it is also the most expensive. This chapter covers two things. The first is how to decide whether you need one. The second is how to package one so other apps can use it.
Decide before you embed
Ask what you actually need from the native side. Most of the time it is one of these:
- A native behavior, such as a sensor, a file picker, or a payment sheet. This needs no embedded view at all.
- A picture produced by native code, such as camera frames, decoded video, or a GPU render. A texture can carry it.
- A widget that exists only natively, such as a full map SDK, a web engine, or an ad view. This is where platform views fit.
Alternative 1: a pure Flutter widget
Flutter draws every pixel itself, so many things that look native can be rebuilt in Dart. Check first whether you really need the native control.
- Buttons, switches, sliders, and navigation bars exist as Material and Cupertino widgets.
- Custom charts, gauges, and signature pads fit
CustomPainter. - Rich text, lists, and forms are built into the framework.
A pure Flutter widget avoids the extra composition work. It also has no gesture arena boundary, no per-platform code, and works on desktop and web unchanged. If a pub.dev package already implements the widget in Dart, prefer it over writing native code.
The cost is fidelity. You will not get platform text selection behavior for free, accessibility details can differ, and you must track OS design changes yourself.
Alternative 2: an existing plugin
Several widely used native views already ship as plugins. Examples are webview_flutter, google_maps_flutter, and video_player. They solve the hard parts for you: composition modes, gesture setup, and lifecycle cleanup. Check the package's platform support table and open issues before you build your own.
Alternative 3: a texture
A Texture widget shows frames that native code renders into a GPU buffer. Flutter composites that buffer like an image, so there is no native view in the hierarchy. This gives you:
- Smooth scrolling and normal z-ordering with other Flutter widgets.
- No native touch handling. You must forward pointer events yourself through a channel.
- No native widgets, only pixels.
The Dart side asks native code for a texture id and then shows it:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeTextureView extends StatefulWidget {
const NativeTextureView({super.key});
@override
State<NativeTextureView> createState() => _NativeTextureViewState();
}
class _NativeTextureViewState extends State<NativeTextureView> {
static const MethodChannel _channel =
MethodChannel('com.example.app/texture');
int? _textureId;
@override
void initState() {
super.initState();
_channel.invokeMethod<int>('create').then((id) {
if (mounted) {
setState(() => _textureId = id);
} else if (id != null) {
_channel.invokeMethod<void>('dispose');
}
});
}
@override
void dispose() {
if (_textureId != null) {
_channel.invokeMethod<void>('dispose');
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final id = _textureId;
if (id == null) {
return const SizedBox(
width: 200,
height: 200,
child: Center(child: CircularProgressIndicator()),
);
}
return SizedBox(width: 200, height: 200, child: Texture(textureId: id));
}
}On Android, the plugin gets a TextureRegistry from its binding, creates a surface texture entry, and draws into it. This example fills the texture with a solid color. A real plugin would draw camera frames or a render here.
import android.graphics.Color
import android.view.Surface
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.TextureRegistry
class TexturePlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var channel: MethodChannel
private var textures: TextureRegistry? = null
private var entry: TextureRegistry.SurfaceTextureEntry? = null
private var surface: Surface? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
textures = binding.textureRegistry
channel = MethodChannel(binding.binaryMessenger, "com.example.app/texture")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"create" -> {
val e = textures!!.createSurfaceTexture()
e.surfaceTexture().setDefaultBufferSize(400, 400)
val s = Surface(e.surfaceTexture())
val canvas = s.lockCanvas(null)
canvas.drawColor(Color.BLUE)
s.unlockCanvasAndPost(canvas)
entry = e
surface = s
result.success(e.id())
}
"dispose" -> {
surface?.release()
entry?.release()
surface = null
entry = null
result.success(null)
}
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
surface?.release()
entry?.release()
}
}On iOS you implement the FlutterTexture protocol, return a CVPixelBuffer from copyPixelBuffer(), register the texture with registrar.textures(), and call textureFrameAvailable whenever a new frame is ready. Newer Flutter versions also offer SurfaceProducer on Android, which survives surface recreation better. Check the current API for your Flutter version before copying code.
Alternative 4: no UI at all
Often the native "view" was only a way to reach a native capability. If you need a result and not a widget, use a different tool:
MethodChannelfor simple request and response calls.- Pigeon, which generates typed channel code for both sides, so you avoid string method names and manual casts.
dart:ffiwithffigen(C and Objective-C) orjnigen(Java and Kotlin) to call native APIs directly from Dart.
Comparing the options
| Option | Native widgets | Native touch input | Scroll and z-order cost | Platforms |
|---|---|---|---|---|
| Pure Flutter widget | No | No (Flutter handles it) | None | All |
| Existing plugin | Yes, hidden from you | Handled for you | Depends on the plugin | Per plugin |
| Texture | No, pixels only | No, forward manually | Low | Android, iOS, others |
| Platform view | Yes | Yes | Highest | Android, iOS |
Shipping a platform view as a plugin
If you want several apps to share the view, move the native code out of MainActivity and AppDelegate and into a plugin package. A plugin registers its own factory when the engine starts, so the host app needs no manual setup.
Create the package:
flutter create --template=plugin --platforms=android,ios native_labelThis generates a package with lib/, android/, ios/, and an example/ app. Use the example app to run and test the view, as you would a normal app.
Declare the plugin classes
The pubspec.yaml of the plugin tells Flutter which native class to call on each platform:
name: native_label
description: A native text label shown through a platform view.
version: 0.0.1
environment:
sdk: ">=3.3.0 <4.0.0"
flutter: ">=3.19.0"
dependencies:
flutter:
sdk: flutter
flutter:
plugin:
platforms:
android:
package: com.example.native_label
pluginClass: NativeLabelPlugin
ios:
pluginClass: NativeLabelPluginRegister the factory on Android
Move NativeLabel and NativeLabelFactory from the earlier example into the plugin's Android package. Then register the factory from the plugin class, using the registry on the plugin binding:
package com.example.native_label
import io.flutter.embedding.engine.plugins.FlutterPlugin
class NativeLabelPlugin : FlutterPlugin {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
binding.platformViewRegistry.registerViewFactory(
"com.example.native_label/label",
NativeLabelFactory()
)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {}
}Register the factory on iOS
Move the Swift classes into ios/Classes/. The plugin class uses the registrar that Flutter passes to it:
import Flutter
import UIKit
public class NativeLabelPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
registrar.register(
NativeLabelFactory(),
withId: "com.example.native_label/label"
)
}
}The CocoaPods spec in ios/native_label.podspec already lists Classes/**/*, so new Swift files are picked up automatically.
Expose a single Dart widget
Move the AndroidView and UiKitView switch from the first Dart example into the package. Export one widget, so apps never see view type strings:
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.native_label/label';
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': text};
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return AndroidView(
viewType: _viewType,
layoutDirection: Directionality.of(context),
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
case TargetPlatform.iOS:
return UiKitView(
viewType: _viewType,
layoutDirection: Directionality.of(context),
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
default:
return Text(text);
}
}
}The fallback for other platforms shows the same text in a regular Text widget. A plugin that silently renders nothing on desktop or web is a common source of bug reports.
Packaging rules that matter
- Namespace the view type. Use your package name as a prefix, as in
com.example.native_label/label. Two plugins that register the same string collide, and the second registration fails or overrides the first. - Keep the string private. Make it a
_viewTypeconstant in the package and export only the widget. - Declare only supported platforms. If you do not implement a platform, omit it from
pubspec.yamlso the tool does not try to build it. - Test in the example app. Run it on a real device for each platform, with a scrollable parent and a second Flutter widget overlapping the native view. Those two cases expose most composition and gesture problems.
- Document the limits. State in the README which composition mode you use, what happens inside scrollables, and the minimum OS and Flutter versions.
- Dry run before publishing.
flutter pub publish --dry-runchecks the package metadata, file size, and license before you upload.
When one package becomes several
If you later add web, macOS, or Windows versions, split the plugin into a federated layout:
- An app-facing package with the public widget.
- A platform interface package that defines the contract.
- One implementation package per platform.
This lets other authors add platforms without changing your package. Do not start with this layout for a two-platform plugin. It adds work that you may never need.
Common mistakes
- Using a platform view for something simple. A styled button or a list does not need native code.
- Using a texture for UI that needs touch input. The texture shows pixels only, so every tap must be forwarded and mapped yourself.
- Forgetting to dispose textures. Leaked texture entries keep GPU memory alive. Release them from both the Dart
disposeand the plugin'sonDetachedFromEngine. - Hard-coding the view type in many places. Define it once in the package and use the same string in the Dart, Kotlin, and Swift code. Check that all three agree when a view fails to appear.
- Skipping the fallback branch. Without a default case, running on desktop throws or shows nothing.
Exercise
Your app needs a live camera preview that scrolls inside a ListView, and users never tap the preview itself. Which option fits best, and why would a platform view be a weaker choice?
Show answer
A Texture is the best fit. The camera produces only pixels, and no native input is needed. A texture composites like an image, so scrolling and z-ordering stay cheap. A platform view adds composition cost and a gesture boundary inside the scrolling list, and you would pay both for no benefit.
Exercise
You are moving the NativeLabel view from an app into a plugin called native_label. List the changes needed on Android, on iOS, and in pubspec.yaml so that apps using the plugin need no setup code.
Show answer
Android: move NativeLabel and NativeLabelFactory into the plugin's Android package, and register the factory in NativeLabelPlugin.onAttachedToEngine with binding.platformViewRegistry.registerViewFactory. iOS: move the Swift classes into ios/Classes and register the factory in NativeLabelPlugin.register(with:) using registrar.register(factory, withId:). pubspec.yaml: add flutter.plugin.platforms entries for android (package and pluginClass) and ios (pluginClass). On all three sides, use the same namespaced view type, such as com.example.native_label/label.
Exercise
Two plugins in one app both register the view type "native_view". What can go wrong, and how do you prevent it?
Show answer
Both registrations use the same string, so one view factory can replace or conflict with the other, and a widget may show the wrong native view or fail to create one. Prevent this by prefixing each view type with the package name, for example com.example.native_label/label, and keeping the string private inside the package.