Sub topic 5
Showing the native view with AndroidView and UiKitView
This chapter covers the Dart side of a platform view. It assumes you can read basic Flutter code (StatelessWidget, StatefulWidget, build). It also assumes you have a native view registered under a view type string on Android and iOS, as the previous two chapters showed. Here you place that view in the widget tree, choose the right widget for each platform, and avoid the usual errors.
What the two widgets do
AndroidView and UiKitView are ordinary Flutter widgets. Each one asks the engine to create a native view through the factory registered under a view type string. Each then reserves a rectangle in the widget tree where that native view is shown.
The widgets share most of their constructor and differ in which native side they talk to.
| Parameter | Meaning | Notes |
|---|---|---|
| `viewType` | String that selects the native factory | Required. Must match the registered string exactly. |
| `layoutDirection` | `TextDirection` given to the native view | Optional on both widgets. If omitted, the ambient `Directionality` is used. |
| `creationParams` | Data passed to the factory's `create` method | Optional. Must be encodable by the codec. |
| `creationParamsCodec` | Codec that encodes `creationParams` | Required when `creationParams` is not null. |
| `onPlatformViewCreated` | Callback with the new view's integer id | Used for per-view channels. |
| `gestureRecognizers` | Set of recognizers the native view may claim | Covered in the gesture chapter. |
| `hitTestBehavior` | How the view takes part in hit testing | Defaults to `opaque`. |
Both widgets are defined in package:flutter/services.dart, which is why the example imports it.
Choosing the widget by platform
A native view exists only on the platform that implemented it, so the Dart code must pick the widget at build time. The widget below returns an AndroidView on Android, a UiKitView on iOS, and a plain Text elsewhere.
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.app/native_label';
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': text};
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
case TargetPlatform.iOS:
return UiKitView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
default:
return const Text('Native view is not supported on this platform');
}
}
}Three details are worth noting.
- One constant for the view type.
viewTypeis astatic const, so the string appears once in Dart. The Kotlin and Swift registrations must use the same text, including case and slashes. - The same parameters on both sides. The map is built once and passed to whichever widget is chosen. The Android factory and the iOS factory both read the key
text, so the two native views behave the same. - A fallback. The
defaultbranch covers desktop and web. Without it, theswitchwould not compile, becauseTargetPlatformhas more values than two.
Gotcha: defaultTargetPlatform on the web
On the web, defaultTargetPlatform reports the platform of the browser's host device. A Flutter web app opened in Chrome on an Android phone sees TargetPlatform.android. It would then build an AndroidView, which the web engine cannot show. Check kIsWeb first:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
bool get supportsNativeViews =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
class SafeNativeLabel extends StatelessWidget {
const SafeNativeLabel({super.key, required this.text});
final String text;
static const String viewType = 'com.example.app/native_label';
@override
Widget build(BuildContext context) {
if (!supportsNativeViews) {
return Text(text);
}
final params = <String, dynamic>{'text': text};
return defaultTargetPlatform == TargetPlatform.android
? AndroidView(
viewType: viewType,
creationParams: params,
creationParamsCodec: const StandardMessageCodec(),
)
: UiKitView(
viewType: viewType,
creationParams: params,
creationParamsCodec: const StandardMessageCodec(),
);
}
}This version also falls back to a Flutter Text that shows the same content, which is a better fallback than an error message.
What happens when the widget builds
The widget does not create the native view itself. It tells the engine to do so, and the engine looks up the factory.
Each widget instance gets a unique integer id. The factory receives the same id on the native side, and onPlatformViewCreated gives it to Dart. The creation is asynchronous, so the first frame may show an empty rectangle before the native view appears.
If the lookup fails, because the factory was never registered or the string differs, creation fails. You see a platform exception in the log, such as Unregistered view type, and the rectangle stays blank.
Sizing and layout
A native view has no intrinsic size from Flutter's point of view. The widget fills the largest size its parent allows, so it follows normal constraint rules.
- In a
Column,ListViewor any other parent that gives unbounded height, the widget throws a layout error. Wrap it in aSizedBox,AspectRatioorExpandedfirst. - In a parent with fixed constraints, such as
SizedBox(height: 200), the native view is resized to match. The native view receives the new size, so its own layout code (AndroidonMeasure/onLayout, iOS Auto Layout) runs again.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: DemoPage()));
}
class DemoPage extends StatelessWidget {
const DemoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Platform view demo')),
body: const Column(
children: [
Text('Flutter text above'),
SizedBox(
height: 80,
width: double.infinity,
child: NativeLabel(text: 'Hello from native'),
),
Text('Flutter text below'),
],
),
);
}
}This page assumes NativeLabel from the first listing is defined in the same file or imported. The SizedBox gives the label a fixed 80-pixel-tall slot, which avoids the unbounded-height error.
Flutter widgets above and below the native view
The native view takes part in painting order like any other widget. A Flutter widget placed above it in a Stack is drawn over it, and a widget placed below is covered. How well this works depends on the composition mode the platform uses, a topic for a later chapter. Two practical rules apply for now:
- Overlays such as dialogs,
SnackBars, and bottom sheets normally appear above platform views and work as expected. - Animations and transforms applied to a platform view, such as rotation, opacity, and clipping, are limited or can be slow, depending on the platform. Test these on a real device before you rely on them.
Keeping the view stable across rebuilds
Creating a native view is expensive, so avoid rebuilding it needlessly.
- Keep the widget's position in the tree stable. If the widget moves to a different parent, or its
Keychanges, Flutter disposes the old native view and creates a new one. The new view loses any state it held. - Changing
creationParamsdoes not update the view. Parameters are read only when the native view is created. Iftextchanges later, the existing native view keeps showing the old text. For updates, either give the widget a newValueKeyto force recreation, or send a message over a per-view channel (the next chapters cover this). - Scrolling lists. In a
ListView, off-screen children are disposed. A native view scrolled away is destroyed, and a new one is created when it returns. If that is too costly, keep a small number of native views alive outside the list.
The ValueKey approach looks like this:
import 'package:flutter/material.dart';
class KeyedLabel extends StatelessWidget {
const KeyedLabel({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
// A new key for each text value recreates the native view.
return SizedBox(
height: 60,
child: NativeLabel(key: ValueKey(text), text: text),
);
}
}This is simple but destroys and rebuilds the whole native view on every change. Use it for rare changes only.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank rectangle and an `Unregistered view type` log message | The view type string differs between Dart and native, or the factory was not registered | Compare the strings character by character. Confirm registration runs at startup (`configureFlutterEngine` on Android, app delegate or plugin registration on iOS). |
| `Vertical viewport was given unbounded height` or a similar layout error | The widget sits in an unbounded parent | Wrap it in `SizedBox`, `Expanded` or a similar widget with a bounded size. |
| Native view shows empty or default data | `creationParams` is null, or the native side reads the wrong key | Print the arguments in the factory. Check key names and types. |
| Exception about a missing codec | `creationParams` was provided without `creationParamsCodec` | Pass `const StandardMessageCodec()`. |
| App crashes on the web with a `dart:io` error | `Platform.isAndroid` was used | Switch to `defaultTargetPlatform` and check `kIsWeb`. |
| Text shows once and never changes | Parameters are read only at creation | Use a key to recreate the view, or a per-view channel to update it. |
| Android view fails on old devices | `AndroidView` needs a minimum Android API level (23 in current Flutter versions) | Raise `minSdkVersion`, or fall back to a Flutter widget. |
Testing the Dart side
Widget tests run on the host machine, not on a device, so no native view is created. You can still test the platform choice:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows fallback text on unsupported platforms', (tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
await tester.pumpWidget(
const MaterialApp(home: NativeLabel(text: 'hi')),
);
expect(find.text('Native view is not supported on this platform'),
findsOneWidget);
});
}The test sets the override to Linux and resets it in a teardown, as Flutter's test framework requires, and asserts that the fallback appears. It assumes NativeLabel is imported from your app. Testing the Android and iOS branches needs a mock for the platform views channel and is usually left to integration tests on real devices.
Summary of the Dart-side contract
- Use one
viewTypeconstant, identical to the native registration string. - Choose
AndroidVieworUiKitViewwithdefaultTargetPlatform, and checkkIsWebfirst. - Pass initial data through
creationParamswith a matching codec, knowing it is read once. - Give the widget bounded constraints.
- Keep its place in the tree stable, because moving or rekeying it destroys the native view.
Exercise
Your app shows a UiKitView inside a Column and logs "Vertical viewport was given unbounded height" once the widget is placed in a ListView. Separately, after the parent calls setState with a new text value, the native label still shows the old text. Name the fix for each problem.
Show answer
For the layout error, give the widget a bounded height, for example by wrapping it in SizedBox(height: ...) or AspectRatio, because a ListView supplies unbounded height along its scroll axis. For the stale text, remember that creationParams is read only when the native view is created. Either give the widget a ValueKey(text) so Flutter recreates the view when the text changes, or open a per-view MethodChannel using the id from onPlatformViewCreated and send the new text to the existing view.
Exercise
A teammate writes if (Platform.isAndroid) { return AndroidView(...); } and the Flutter web build crashes at startup of that widget. Explain why, and show the condition you would use instead to decide whether native views are available.
Show answer
Platform comes from dart:io, which is not supported on the web, so using it throws. Use foundation.dart instead: !kIsWeb && (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS). The kIsWeb check matters because on the web defaultTargetPlatform reports the host device, so a browser on an Android phone would otherwise select AndroidView.