Platform Integration
Prerequisites: Flutter fundamentals, Futures and async/await
Flutter covers most UI and logic in Dart, but sometimes you need a platform feature it doesn't provide directly — a device sensor, a platform SDK, or an existing native library.
Plugins first
Most platform features are already wrapped as plugins on pub.dev:
camera, geolocator, url_launcher, shared_preferences,
local_auth, and many more. Each plugin contains Dart code plus native
code for each platform. Always check pub.dev before writing your own.
Platform channels
To call your own native code, send messages over a method channel:
import 'package:flutter/services.dart';
class BatteryService {
static const _channel = MethodChannel('com.example.app/battery');
Future<int?> batteryLevel() async {
try {
return await _channel.invokeMethod<int>('getBatteryLevel');
} on PlatformException catch (e) {
print('Failed: ${e.message}');
return null;
}
}
}
On Android, Kotlin code handles the call:
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.app/battery")
.setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
result.success(manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY))
} else {
result.notImplemented()
}
}
and Swift code does the same on iOS. Messages are asynchronous, so the
Dart side awaits the result.
The pigeon package generates type-safe channel code for both sides
from a single Dart definition, avoiding hand-written string method
names.
FFI: calling C directly
dart:ffi calls C functions directly — with no message passing —
which suits performance-critical native libraries (image codecs, crypto,
databases like SQLite). The ffigen package generates Dart bindings from
C header files.
Web
On the web, Dart talks to JavaScript through dart:js_interop and
the package:web browser APIs, using extension types to describe
JavaScript objects.
Which to use
| Need | Use |
|---|---|
| A common device feature | An existing plugin |
| Your own platform SDK integration | Platform channels / pigeon |
| A fast C library | dart:ffi |
| Browser APIs | dart:js_interop, package:web |