flutter-embedding-native-views
Original:🇺🇸 English
Not Translated
Embeds native Android, iOS, or macOS views into a Flutter app. Use when integrating complex native components like maps or web views.
3installs
Sourcegsmlg-dev/code-agent
Added on
NPX Install
npx skill4agent add gsmlg-dev/code-agent flutter-embedding-native-viewsSKILL.md Content
Integrating Platform Views and Web Content
Contents
- Platform Views Architecture
- Web Embedding Architecture
- Workflow: Implementing Android Platform Views
- Workflow: Implementing iOS Platform Views
- Workflow: Embedding Flutter in Web Applications
- Examples
Platform Views Architecture
Platform Views allow embedding native views (Android, iOS, macOS) directly into a Flutter application, enabling the application of transforms, clips, and opacity from Dart.
Android Implementations (API 23+)
Choose the appropriate implementation based on your performance and fidelity requirements:
- Hybrid Composition: Renders Flutter content into a texture and uses to compose both.
SurfaceFlinger- Pros: Best performance and fidelity for Android views.
- Cons: Lowers overall application FPS. Certain Flutter widget transformations will not work.
- Texture Layer (Texture Layer Hybrid Composition): Renders Platform Views into a texture. Flutter draws them via the texture and renders its own content directly into a Surface.
- Pros: Best performance for Flutter rendering. All transformations work correctly.
- Cons: Quick scrolling (e.g., WebViews) can be janky. is problematic (breaks accessibility). Text magnifiers break unless Flutter is rendered into a
SurfaceView.TextureView
iOS & macOS Implementations
- iOS: Uses Hybrid Composition exclusively. The native is appended to the view hierarchy.
UIView- Limitations: and
ShaderMaskwidgets are not supported.ColorFilteredhas composition limitations.BackdropFilter
- Limitations:
- macOS: Uses Hybrid Composition ().
NSView- Limitations: Not fully functional in current releases (e.g., gesture support is unavailable).
Performance Mitigation
Mitigate performance drops during complex Dart animations by rendering a screenshot of the native view as a placeholder texture while the animation runs.
Web Embedding Architecture
Embed Flutter into existing web applications (Vanilla JS, React, Angular, etc.) using either Full Page mode or Embedded (Multi-view) mode.
- Full Page Mode: Flutter takes over the entire browser window. Use an if you need to constrain the Flutter app without modifying the Flutter bootstrap process.
iframe - Embedded Mode (Multi-view): Render Flutter into specific HTML elements (s). Requires
divduring engine initialization.multiViewEnabled: true- Manage views from JavaScript using and
app.addView().app.removeView() - In Dart, replace with
runApp.runWidget - Manage the dynamic list of views using and render them using
WidgetsBinding.instance.platformDispatcher.viewsandViewCollectionwidgets.View
- Manage views from JavaScript using
Workflow: Implementing Android Platform Views
Follow this sequential workflow to implement a Platform View on Android.
Task Progress:
- 1. Determine the composition mode (Hybrid vs. Texture Layer).
- 2. Implement the Dart widget.
- 3. Implement the native Android View and Factory.
- 4. Register the Platform View in the Android host.
- 5. Run validator -> review rendering -> fix manual invalidation issues.
1. Dart Implementation
If using Hybrid Composition, use , , and .
If using Texture Layer, use the widget.
PlatformViewLinkAndroidViewSurfacePlatformViewsService.initSurfaceAndroidViewAndroidView2. Native Implementation
Create a class implementing that returns your native .
Create a factory extending to instantiate your view.
io.flutter.plugin.platform.PlatformViewandroid.view.ViewPlatformViewFactory3. Registration
Register the factory in your (or plugin) using .
MainActivity.ktflutterEngine.platformViewsController.registry.registerViewFactoryNote: If your native view uses or , manually call on the View or its parent when content changes, as they do not invalidate themselves automatically.
SurfaceViewSurfaceTextureinvalidateWorkflow: Implementing iOS Platform Views
Follow this sequential workflow to implement a Platform View on iOS.
Task Progress:
- 1. Implement the Dart widget using .
UiKitView - 2. Implement the native iOS View () and Factory (
FlutterPlatformView).FlutterPlatformViewFactory - 3. Register the Platform View in or the plugin registrar.
AppDelegate.swift - 4. Run validator -> review composition limitations -> fix unsupported filters.
Workflow: Embedding Flutter in Web Applications
Follow this sequential workflow to embed Flutter into an existing web DOM.
Task Progress:
- 1. Update to enable multi-view.
flutter_bootstrap.js - 2. Update to use
main.dartandrunWidget.ViewCollection - 3. Implement JavaScript logic to add/remove host elements.
- 4. Run validator -> review view constraints -> fix CSS conflicts.
1. JavaScript Configuration
In , initialize the engine with .
Use the returned object to add views: .
flutter_bootstrap.jsmultiViewEnabled: trueappapp.addView({ hostElement: document.getElementById('my-div') })2. Dart Configuration
Replace with .
Create a root widget that listens to .
Map over to create a widget for each attached , and wrap them all in a .
runApp()runWidget()WidgetsBindingObserver.didChangeMetricsWidgetsBinding.instance.platformDispatcher.viewsViewFlutterViewViewCollectionExamples
Example: Android Texture Layer (Dart)
dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeAndroidView extends StatelessWidget {
Widget build(BuildContext context) {
const String viewType = 'my_native_view';
final Map<String, dynamic> creationParams = <String, dynamic>{};
return AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
}
}Example: Web Multi-View Initialization (JavaScript)
javascript
_flutter.loader.load({
onEntrypointLoaded: async function(engineInitializer) {
let engine = await engineInitializer.initializeEngine({
multiViewEnabled: true,
});
let app = await engine.runApp();
// Add a view to a specific DOM element
let viewId = app.addView({
hostElement: document.querySelector('#flutter-host-container'),
initialData: { customData: 'Hello from JS' }
});
}
});Example: Web Multi-View Root Widget (Dart)
dart
import 'dart:ui' show FlutterView;
import 'package:flutter/widgets.dart';
void main() {
runWidget(MultiViewApp(viewBuilder: (context) => const MyEmbeddedWidget()));
}
class MultiViewApp extends StatefulWidget {
final WidgetBuilder viewBuilder;
const MultiViewApp({super.key, required this.viewBuilder});
State<MultiViewApp> createState() => _MultiViewAppState();
}
class _MultiViewAppState extends State<MultiViewApp> with WidgetsBindingObserver {
Map<Object, Widget> _views = {};
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_updateViews();
}
void didChangeMetrics() => _updateViews();
void _updateViews() {
final newViews = <Object, Widget>{};
for (final FlutterView view in WidgetsBinding.instance.platformDispatcher.views) {
newViews[view.viewId] = _views[view.viewId] ?? View(
view: view,
child: Builder(builder: widget.viewBuilder),
);
}
setState(() => _views = newViews);
}
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
Widget build(BuildContext context) {
return ViewCollection(views: _views.values.toList(growable: false));
}
}