YouTip LogoYouTip

Flutter Platform Channels

This section will introduce how to use Platform Channels to call native platform code in Flutter. * * * ## Platform Channel Overview Platform Channels allow Dart code to communicate with native platforms (iOS/Android). | Type | Description | | --- | --- | | MethodChannel | Method channel, used to call platform methods | | EventChannel | Event channel, used for streaming data | * * * ## Dart Side Calling ## Example: MethodChannel Usage import'package:flutter/services.dart'; // Define channel class PlatformChannel { static const MethodChannel _channel = MethodChannel('my_app/channel'); // Call native method - Get battery level static Future getBatteryLevel() async { try{ final int batteryLevel = await _channel.invokeMethod('getBatteryLevel'); return batteryLevel; } on PlatformException catch(e){ print('Failed to get battery level: ${e.message}'); return-1; } } // Call native method - Show Toast static Future showToast(String message) async { try{ await _channel.invokeMethod('showToast',{'message': message}); } on PlatformException catch(e){ print('Failed to show Toast: ${e.message}'); } } // Call native method - Get device information static Future<Map> getDeviceInfo() async { try{ final result = await _channel.invokeMapMethod('getDeviceInfo'); return result ??{}; } on PlatformException catch(e){ print('Failed to get device info: ${e.message}'); return{}; } } } // Usage example class MyWidget extends StatelessWidget { const MyWidget({super.key}); @override Widget build(BuildContext context){ return ElevatedButton( onPressed:() async { final battery = await PlatformChannel.getBatteryLevel(); print('Battery level: $battery%'); }, child:const Text('Get Battery Level'), ); } } * * * ## Android Side Implementation (Kotlin) ## Example: Android Side Code // MainActivity.kt package com.example.my_app import android.os.Bundle import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "my_app/channel" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL) .setMethodCallHandler { call, result -> when (call.method) { "getBatteryLevel" -> { val batteryLevel = getBatteryLevel() if (batteryLevel != -1) { result.success(batteryLevel) } else { result.error("UNAVAILABLE", "Unable to get battery level", null) } } "showToast" -> { val message = call.argument("message") showToast(message!!) result.success(null) } else -> { result.notImplemented() } } } } private fun getBatteryLevel(): Int { return try { val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) } catch (e: Exception) { -1 } } private fun showToast(message: String) { android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show() } } * * * ## iOS Side Implementation (Swift) ## Example: iOS Side Code // AppDelegate.swift import Flutter import UIKit @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { private let CHANNEL = "my_app/channel" override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let controller = window?.rootViewController as! FlutterViewController let channel = FlutterMethodChannel( name: CHANNEL, binaryMessenger: controller.binaryMessenger ) channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in switch call.method { case "getBatteryLevel": self.getBatteryLevel(result: result) case "showToast": if let args = call.arguments as? [String: Any], let message = args as? String { self.showToast(message: message) result(nil) } default: result(FlutterMethodNotImplemented) } } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } private func getBatteryLevel(result: @escaping FlutterResult) { UIDevice.current.isBatteryMonitoringEnabled = true let batteryLevel = UIDevice.current.batteryLevel if batteryLevel Platform Channels are the primary way for Flutter to communicate with native code, commonly used for calling system APIs, hardware functions, or using third-party native SDKs.
← Flutter Build ReleaseFlutter Images β†’