0
0
Fluttermobile~5 mins

Why platform channels bridge native code in Flutter

Choose your learning style9 modes available
Introduction

Platform channels let Flutter apps talk to native code on Android and iOS. This helps use features Flutter doesn't have by itself.

When you want to use a phone feature Flutter doesn't support yet, like sensors or camera controls.
When you need to run native code for better performance or access system APIs.
When you want to reuse existing native code in your Flutter app.
When you want to handle platform-specific tasks like notifications or background services.
When you need to get data from native libraries or SDKs.
Syntax
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.

Examples
This example calls native code to get the battery level from the device.
Flutter
final platform = MethodChannel('samples.flutter.dev/battery');

Future<int> getBatteryLevel() async {
  final int batteryLevel = await platform.invokeMethod('getBatteryLevel');
  return batteryLevel;
}
This example listens for native code to ask Flutter to show a toast message.
Flutter
platform.setMethodCallHandler((call) async {
  if (call.method == 'showToast') {
    final message = call.arguments as String;
    // Show toast on Flutter side
    return 'Toast shown';
  }
  return null;
});
Sample App

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.

Flutter
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'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

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.

Summary

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.