Platform Integration

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Flutter draws its own pixels, but a real app still needs the operating system: the camera, GPS, battery state, secure hardware, a native SDK. Trailhead needs two of them for its "log a hike" screen, a photo and a position. Most of the time a published plugin already does the job, and this page shows both how to use one and how to write your own when none exists. Saved photos and positions then flow into the data layer from Data, Storage and Networking. For the equivalent in other stacks, see React Native and Kotlin Multiplatform; the overview is in Hybrid Apps.

Choosing a Mechanism

Mechanism Use it for Notes

Existing plugin from pub.dev

Common features (camera, location, files).

Always check first; it is almost free.

MethodChannel / EventChannel

A few calls or a stream to your own native code.

Asynchronous, messages are serialised with the standard codec.

Pigeon

Many calls, or a team that wants compile-time checks.

Generates Dart, Kotlin, Swift and other sides from one Dart definition.

dart:ffi

Calling a C library synchronously with little overhead.

Generated bindings with ffigen; jnigen for Java and Kotlin APIs.

Platform view

Showing a native widget (map, web view) inside Flutter.

More expensive than a Flutter widget; use only when needed.

Platform Channels

A channel is a named, asynchronous message pipe between Dart and the host platform. The Dart side:

import 'package:flutter/services.dart';

class BatteryService {
  static const _channel = MethodChannel('com.example.trailhead/battery');

  Future<int> level() async {
    try {
      final result = await _channel.invokeMethod<int>('getBatteryLevel');
      return result ?? -1;
    } on PlatformException catch (e) {
      throw StateError('Battery unavailable: ${e.message}');
    }
  }
}
sequenceDiagram participant Dart as Dart (BatteryService) participant Engine as Flutter engine participant Host as Kotlin or Swift handler participant OS as Operating system Dart->>Engine: invokeMethod getBatteryLevel Engine->>Host: Encoded message on the platform thread Host->>OS: Read battery level OS-->>Host: 83 Host-->>Engine: result(83) Engine-->>Dart: Future completes with 83

Android side (Kotlin)

class MainActivity : FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.trailhead/battery")
            .setMethodCallHandler { call, result ->
                if (call.method == "getBatteryLevel") {
                    val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
                    val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
                    if (level >= 0) result.success(level) else result.error("UNAVAILABLE", "No battery", null)
                } else {
                    result.notImplemented()
                }
            }
    }
}

iOS side (Swift)

import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    let controller = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(
      name: "com.example.trailhead/battery",
      binaryMessenger: controller.binaryMessenger)
    channel.setMethodCallHandler { call, result in
      guard call.method == "getBatteryLevel" else { return result(FlutterMethodNotImplemented) }
      UIDevice.current.isBatteryMonitoringEnabled = true
      let level = UIDevice.current.batteryLevel
      if level < 0 { result(FlutterError(code: "UNAVAILABLE", message: "No battery", details: nil)) }
      else { result(Int(level * 100)) }
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

The exact project template changes between Flutter releases (for example how the iOS entry point is annotated), so follow the generated files in your project and the official guide listed under References.

EventChannel for streams

An EventChannel carries a continuous stream from native to Dart, such as sensor updates:

const events = EventChannel('com.example.trailhead/compass');

Stream<double> headings() =>
    events.receiveBroadcastStream().map((event) => event as double);

The native side implements a stream handler (EventChannel.StreamHandler on Android, FlutterStreamHandler on iOS) whose onListen starts sending events and whose onCancel stops them.

Pigeon

String method names and untyped maps are error-prone. Pigeon generates both ends from a Dart description, so a signature change fails to compile on every platform:

import 'package:pigeon/pigeon.dart';

class HikeSummary {
  HikeSummary({required this.distanceKm, required this.durationMinutes});
  double distanceKm;
  int durationMinutes;
}

@HostApi()
abstract class HikeStatsApi {
  HikeSummary summarise(String trailId);
}

Running the generator (dart run pigeon --input pigeons/hike_stats.dart, with output paths set by ConfigurePigeon) produces a Dart client plus Kotlin and Swift interfaces to implement.

FFI: dart:ffi, ffigen and jnigen

dart:ffi calls C functions directly, without channel serialisation, and can be synchronous:

import 'dart:ffi' as ffi;
import 'dart:io' show Platform;

typedef _AddNative = ffi.Int32 Function(ffi.Int32, ffi.Int32);
typedef _AddDart = int Function(int, int);

final ffi.DynamicLibrary _lib = Platform.isAndroid
    ? ffi.DynamicLibrary.open('libtrailmath.so')
    : ffi.DynamicLibrary.process();

final _AddDart add = _lib.lookupFunction<_AddNative, _AddDart>('add');

Writing these typedefs by hand does not scale, so the ffigen package generates Dart bindings from C headers, and jnigen generates bindings for Java and Kotlin APIs on Android. The official guide to C interop and the package_ffi template describe how to build and bundle native code with the app.

Federated Plugins and Creating One

A plugin is a package with platform code. Popular plugins are federated: an app-facing package defines the Dart API, a platform-interface package defines the contract, and one implementation package exists per platform (for example camera, camera_platform_interface, camera_android_camerax, camera_avfoundation). Anyone can then add a new platform without touching the app-facing package.

flutter create --template=plugin --platforms=android,ios trailhead_haptics
flutter create --template=plugin_ffi trailhead_math

The generated project contains the Dart API, native sources per platform, and an example/ app for manual testing.

Permissions

Plugins declare what they need, but the app still owns the permission text. For Trailhead:

<!-- android/app/src/main/AndroidManifest.xml -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- ios/Runner/Info.plist -->
<key>NSCameraUsageDescription</key>
<string>Trailhead uses the camera to attach a photo to your hike.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Trailhead records where you finished your hike.</string>

A missing Info.plist key crashes the app on iOS the moment the API is used, so add the keys before testing on a device. Permissions are also requested at run time; ask in context (when the user taps the button), explain why, and handle a permanent denial by pointing to system settings.

Log a Hike: Camera and Location

With camera 0.12.2 and geolocator 14.1.2:

flutter pub add camera geolocator
Future<Position?> currentPosition() async {
  if (!await Geolocator.isLocationServiceEnabled()) return null;

  var permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
  }
  if (permission == LocationPermission.denied ||
      permission == LocationPermission.deniedForever) {
    return null;
  }
  return Geolocator.getCurrentPosition(
    locationSettings: const LocationSettings(accuracy: LocationAccuracy.high),
  );
}
class CameraScreen extends StatefulWidget {
  const CameraScreen({super.key});
  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  CameraController? _controller;

  @override
  void initState() {
    super.initState();
    _init();
  }

  Future<void> _init() async {
    final cameras = await availableCameras();
    final controller = CameraController(cameras.first, ResolutionPreset.medium);
    await controller.initialize();
    if (!mounted) return;
    setState(() => _controller = controller);
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  Future<void> _take() async {
    final file = await _controller!.takePicture();
    if (mounted) Navigator.of(context).pop(file.path);
  }

  @override
  Widget build(BuildContext context) {
    final controller = _controller;
    if (controller == null || !controller.value.isInitialized) {
      return const Center(child: CircularProgressIndicator());
    }
    return Scaffold(
      body: CameraPreview(controller),
      floatingActionButton: FloatingActionButton(
        onPressed: _take,
        child: const Icon(Icons.camera_alt),
      ),
    );
  }
}

The returned path goes into the HikeDraft with the latitude and longitude, then to the repository for upload. Large camera photos should be resized before upload; see Kotlin Multiplatform and Flutter.

Platform Views

A platform view embeds a native widget. On Android the widget is AndroidView (or hybrid composition), on iOS UiKitView. A plugin such as a maps or web view package normally hides this; writing one yourself means registering a view factory on the native side and referencing its viewType from Dart. Each platform view costs memory and can complicate scrolling and animation, so prefer a pure Flutter widget when one exists.

Add-to-App

Flutter can also be embedded in an existing native app as a module, using a FlutterEngine (optionally pre-warmed and cached) with FlutterActivity on Android or FlutterViewController on iOS. It suits teams that want to migrate one screen or flow at a time. The conceptual counterpart for React Native is brownfield integration in the React Native section. Engine and rendering details are in Architecture and Rendering.

Next: Testing, including how to fake a platform channel in tests, and the Flutter Cheat Sheet.