Sub topic 10
Android composition modes and PlatformViewLink
This chapter assumes you have read the previous chapters. You should know how a view type string, a PlatformViewFactory and a Dart widget fit together. You should also be able to read basic Kotlin and Dart. Here you will learn how Flutter on Android puts a native view on screen, what the available composition modes are, and how to choose one in Dart with PlatformViewLink.
Why Android has several modes
Flutter draws its own pixels with its own renderer. A native Android View is drawn by the Android view system. To show both in one widget tree, Flutter has to merge two rendering pipelines. Android offers more than one way to do this, and each way trades speed, correctness and compatibility differently.
Flutter has used three approaches over time:
- Virtual display (VD). The native view renders into an off-screen
VirtualDisplay. Flutter reads that output as a texture and draws it like any other Flutter content. - Hybrid composition (HC). The native view is attached to the real Android view hierarchy, above or between Flutter surfaces. Android composites the result.
- Texture layer hybrid composition (TLHC). The native view lives in the real view hierarchy, but Flutter draws its contents into a texture. The texture is then composited with the rest of the Flutter scene.
The native side does not change between modes. The same PlatformViewFactory and PlatformView classes from the Android chapter work in all of them. The mode is chosen in Dart, by the widget and controller you use.
The three modes compared
| Mode | Where the native view renders | Main strengths | Main costs |
|---|---|---|---|
| Virtual display | Off-screen display, read as a texture | Flutter content stays fast | Input and accessibility are emulated, and some views misbehave |
| Hybrid composition | The real Android view hierarchy | Accurate input, keyboard and accessibility | Can slow Flutter rendering, especially on older Android versions |
| Texture layer hybrid composition | The real view hierarchy, drawn into a texture | Fast Flutter rendering with better fidelity than VD | Some views do not work, such as those containing a `SurfaceView` |
Treat the exact version thresholds as something to verify. The minimum Android API level and the fallback rules have changed between Flutter releases. Check the documentation for the Flutter version you ship.
Virtual display
Virtual display was the original mode. Because the view is not in the real hierarchy, many things that depend on a real hierarchy are emulated or broken. Soft keyboard input, text selection handles, and accessibility focus are common trouble spots. You rarely choose it on purpose today. You are more likely to meet it as a fallback.
Hybrid composition
In hybrid composition the native view is a real child of the Android activity's view hierarchy. Keyboard, focus, text handles, accessibility and system magnifiers behave as they do in a native app. The cost is synchronization. Flutter has to coordinate its raster thread with the Android platform thread so the two surfaces stay aligned. On older Android versions this can reduce Flutter's frame rate while the platform view is on screen.
Texture layer hybrid composition
TLHC is the default for AndroidView in current Flutter releases. The native view is still in the real hierarchy, which gives better input and accessibility than virtual display. Its pixels are drawn into a texture that Flutter composes like any other widget output, so the Flutter side stays fast. Flutter falls back to virtual display when TLHC cannot be used. Two typical cases are an older Android version and a native view that contains a SurfaceView.
How `AndroidView` and `PlatformViewLink` differ
AndroidView is the convenient widget. You give it a view type and parameters. Flutter picks the mode, which is TLHC with a virtual display fallback. You cannot force hybrid composition through it.
PlatformViewLink is the lower-level building block. It does not choose a mode or create a native view. It manages the lifecycle of one platform view and asks you for two things:
onCreatePlatformViewis a function that creates and returns a controller. The controller you create decides the composition mode.surfaceFactoryis a function that returns the widget that displays the view. For Android, that is anAndroidViewSurface.
For hybrid composition, the controller comes from PlatformViewsService.initSurfaceAndroidView. You can also obtain a texture-based controller with PlatformViewsService.initAndroidView, which is what AndroidView uses internally. An older helper, initExpensiveAndroidView, also produces a hybrid composition controller. The Surface variant is the one the current documentation uses.
A widget that selects the mode
The widget below shows both paths side by side. A hybrid flag chooses between the convenient AndroidView and the explicit PlatformViewLink. It uses the same view type and creation parameters as the earlier chapters, so the Kotlin factory registered as com.example.app/native_label works with both.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
class AndroidNativeLabel extends StatelessWidget {
const AndroidNativeLabel({
super.key,
required this.text,
this.hybrid = false,
});
final String text;
final bool hybrid;
static const String viewType = 'com.example.app/native_label';
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': text};
if (!hybrid) {
// Flutter chooses TLHC, falling back to a virtual display if needed.
return AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
}
// Explicit hybrid composition.
return PlatformViewLink(
viewType: viewType,
surfaceFactory: (context, controller) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
},
onCreatePlatformView: (params) {
return PlatformViewsService.initSurfaceAndroidView(
id: params.id,
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
onFocus: () => params.onFocusChanged(true),
)
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
..create();
},
);
}
}Put it on screen with a fixed size, because native views need bounded constraints:
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(
child: SizedBox(
width: 300,
height: 80,
child: AndroidNativeLabel(text: 'Hybrid composition', hybrid: true),
),
),
),
),
);
}The example needs the Kotlin factory from the Android chapter to run. Run it on an Android device or emulator. Flip hybrid to false and compare. A label will look the same in both modes. The differences appear under load, with text input, or with accessibility tools.
What each part of `PlatformViewLink` does
The PlatformViewLink code has several pieces. Each solves a specific problem.
The `params` object
onCreatePlatformView receives a PlatformViewCreationParams. It carries three things you must wire up:
params.idis the unique view id. You pass it to the controller so Flutter and Android agree on which view is meant. It is also the id you would use for a per-viewMethodChannel.params.onPlatformViewCreatedis a callback Flutter needs to be told when the native view exists. Register it withaddOnPlatformViewCreatedListener.params.onFocusChangedis how focus reaches the framework. Calling it withtruewhen the native view gains focus keeps keyboard and focus state consistent.
Calling `create()`
The controller does nothing until you call create(). The cascade ..create() at the end of the expression calls it, then returns the controller as the value of the expression. Leaving it out is a common mistake. The widget appears but no native view is ever made, and you get a blank area.
`AndroidViewSurface`
AndroidViewSurface is the widget that actually shows the native view and routes pointer events to it. It needs the controller, a hit test behavior, and a set of gesture recognizers. The cast controller as AndroidViewController is required because surfaceFactory hands you the base type PlatformViewController.
Gestures and hit testing in the lower-level API
AndroidView accepts gestureRecognizers as an optional argument. In the PlatformViewLink path you pass the same set to AndroidViewSurface. An empty set means Flutter gesture recognizers do not compete for touches, so the native view receives them as is. To make the native view win inside a scrollable parent such as a ListView, add an eager recognizer:
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
Widget buildEagerSurface(
BuildContext context,
PlatformViewController controller,
) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
},
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
}hitTestBehavior controls how the surface responds to pointer events that land on it:
| Value | Behavior |
|---|---|
| `opaque` | The surface absorbs touches, and widgets behind it do not receive them |
| `translucent` | The surface receives touches and widgets behind it can also receive them |
| `transparent` | The surface ignores touches, and only widgets behind it receive them |
opaque suits most views. Use transparent only for display-only native content with Flutter controls on top.
Choosing a mode
Start with the default and move to hybrid composition only when a concrete problem forces you to.
Typical reasons to switch to hybrid composition:
- A native view that contains a
SurfaceView, such as some map or video views, that the texture-based path does not handle. - Text input fields that must show correct soft-keyboard behavior or selection handles.
- Screen reader focus that jumps incorrectly or skips the native view.
Typical reasons to avoid it:
- The view is on screen all the time inside a scrolling, animation-heavy Flutter screen.
- Your app targets Android versions where hybrid composition is known to cost frame rate.
Common errors
- Blank area. You did not call
create()on the controller, or you forgotaddOnPlatformViewCreatedListener. Check the cascade at the end ofonCreatePlatformView. - Type cast exception.
surfaceFactoryreturns aPlatformViewController. Cast it toAndroidViewControllerbefore passing it toAndroidViewSurface. - Layout exception about unbounded constraints. Wrap the view in a
SizedBoxorExpanded. Native views need finite width and height. - View type not found. The string in Dart must match the string passed to
registerViewFactoryexactly. - Scrolling fights the native view. Add a gesture recognizer set as shown above, or accept that the parent scrollable wins.
- Different behavior in release builds or on other devices. The mode, and sometimes the fallback, depends on the Android version. Test on a low-end device with an older OS, not only on the newest emulator.
Checking which mode you actually got
Flutter does not expose a simple public flag that tells you which mode was chosen. Verify by behavior:
- Put a native text field in the view and test the soft keyboard and selection handles.
- Turn on TalkBack and swipe through the screen.
- Open the performance overlay and watch the raster thread while the platform view is visible.
Make your decision from measured results on the devices you support. Avoid deciding from what the documentation implies for a generic device.
Exercise
Your Flutter screen shows a native Android map view using the default AndroidView. Users report that the map is blank on some older phones and that screen reader focus skips it. Which change would you try first, and what must you do in the Dart code to make it work?
Show answer
Switch to hybrid composition by using PlatformViewLink. Return an AndroidViewSurface from surfaceFactory, casting the controller to AndroidViewController. In onCreatePlatformView, call PlatformViewsService.initSurfaceAndroidView with params.id, the view type, creation parameters and codec, and onFocus: () => params.onFocusChanged(true). Then add params.onPlatformViewCreated with addOnPlatformViewCreatedListener and call create(). The Kotlin factory does not change. Afterwards, check frame rate on an older device, because hybrid composition can cost Flutter rendering speed.
Exercise
In a PlatformViewLink, what happens if you build the controller with initSurfaceAndroidView but never call create()?
Show answer
The controller is never asked to create the native view, so the platform view does not appear. The widget shows an empty area, and the factory's create method on the Android side is not called.