Platform channels let Flutter apps talk to native code on Android and iOS. This helps use features Flutter doesn't have by itself.
Why platform channels bridge native code in Flutter
final platform = MethodChannel('channel_name'); // To call native code final result = await platform.invokeMethod('methodName', arguments); // To receive calls from native code platform.setMethodCallHandler((call) async { if (call.method == 'methodName') { return 'response'; } return null; });
The MethodChannel connects Flutter and native code using a unique channel name.
Use invokeMethod to ask native code to do something and get a result back.
final platform = MethodChannel('samples.flutter.dev/battery'); Future<int> getBatteryLevel() async { final int batteryLevel = await platform.invokeMethod('getBatteryLevel'); return batteryLevel; }
platform.setMethodCallHandler((call) async {
if (call.method == 'showToast') {
final message = call.arguments as String;
// Show toast on Flutter side
return 'Toast shown';
}
return null;
});This Flutter app uses a platform channel to ask native code for the battery level. When you tap the button, it shows the battery percentage.
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { static const platform = MethodChannel('samples.flutter.dev/battery'); String _batteryLevel = 'Unknown battery level.'; Future<void> _getBatteryLevel() async { String batteryLevel; try { final int result = await platform.invokeMethod('getBatteryLevel'); batteryLevel = 'Battery level is $result%.'; } on PlatformException catch (e) { batteryLevel = 'Failed to get battery level: ${e.message}'; } setState(() { _batteryLevel = batteryLevel; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Battery Level Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_batteryLevel), ElevatedButton( onPressed: _getBatteryLevel, child: const Text('Get Battery Level'), ), ], ), ), ), ); } }
Platform channels work by sending messages between Flutter and native code asynchronously.
You must implement the native side code separately in Android (Kotlin/Java) and iOS (Swift/Objective-C).
Always handle errors because native calls can fail or be unavailable on some devices.
Platform channels let Flutter apps use native device features.
They send messages between Flutter and native code using a named channel.
This helps Flutter apps do things they can't do alone.