Flutter プラットフォーム固有コード
このセクションでは、プラットフォームチャネル(Platform Channels)を使用して Flutter でネイティブプラットフォームコードを呼び出す方法を紹介します。
プラットフォームチャネルの概要
プラットフォームチャネルを使用すると、Dart コードがネイティブプラットフォーム(iOS/Android)と通信できます。
| タイプ | 説明 |
|---|---|
| MethodChannel | メソッドチャネル。プラットフォームのメソッドを呼び出すために使用 |
| EventChannel | イベントチャネル。ストリーミングデータに使用 |
Dart側からの呼び出し
例:MethodChannel の使用方法
import 'package:flutter/services.dart';
// チャネルを定義
class PlatformChannel {
static const MethodChannel _channel = MethodChannel('my_app/channel');
// ネイティブメソッドを呼び出し - バッテリー残量を取得
static Future<int> getBatteryLevel() async {
try {
final int batteryLevel = await _channel.invokeMethod('getBatteryLevel');
return batteryLevel;
} on PlatformException catch (e) {
print('バッテリー残量の取得に失敗: ${e.message}');
return -1;
}
}
// ネイティブメソッドを呼び出し - Toastを表示
static Future<void> showToast(String message) async {
try {
await _channel.invokeMethod('showToast', {'message': message});
} on PlatformException catch (e) {
print('Toastの表示に失敗: ${e.message}');
}
}
// ネイティブメソッドを呼び出し - デバイス情報を取得
static Future<Map<String, dynamic>> getDeviceInfo() async {
try {
final result = await _channel.invokeMapMethod('getDeviceInfo');
return result ?? {};
} on PlatformException catch (e) {
print('デバイス情報の取得に失敗: ${e.message}');
return {};
}
}
}
// 使用例
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
final battery = await PlatformChannel.getBatteryLevel();
print('バッテリー残量: $battery%');
},
child: const Text('バッテリー残量を取得'),
);
}
}
// チャネルを定義
class PlatformChannel {
static const MethodChannel _channel = MethodChannel('my_app/channel');
// ネイティブメソッドを呼び出し - バッテリー残量を取得
static Future<int> getBatteryLevel() async {
try {
final int batteryLevel = await _channel.invokeMethod('getBatteryLevel');
return batteryLevel;
} on PlatformException catch (e) {
print('バッテリー残量の取得に失敗: ${e.message}');
return -1;
}
}
// ネイティブメソッドを呼び出し - Toastを表示
static Future<void> showToast(String message) async {
try {
await _channel.invokeMethod('showToast', {'message': message});
} on PlatformException catch (e) {
print('Toastの表示に失敗: ${e.message}');
}
}
// ネイティブメソッドを呼び出し - デバイス情報を取得
static Future<Map<String, dynamic>> getDeviceInfo() async {
try {
final result = await _channel.invokeMapMethod('getDeviceInfo');
return result ?? {};
} on PlatformException catch (e) {
print('デバイス情報の取得に失敗: ${e.message}');
return {};
}
}
}
// 使用例
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
final battery = await PlatformChannel.getBatteryLevel();
print('バッテリー残量: $battery%');
},
child: const Text('バッテリー残量を取得'),
);
}
}
Android側の実装(Kotlin)
例:Android側のコード
// 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", "无法获取电池电量", null)
}
}
"showToast" -> {
val message = call.argument<String>("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()
}
}
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", "无法获取电池电量", null)
}
}
"showToast" -> {
val message = call.argument<String>("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側の実装(Swift)
例:iOS側のコード
// 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["message"] 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 < 0 {
result(FlutterError(code: "UNAVAILABLE", message: "无法获取电池电量", details: nil))
} else {
result(Int(batteryLevel * 100))
}
}
private func showToast(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
alert.dismiss(animated: true)
}
}
}
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["message"] 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 < 0 {
result(FlutterError(code: "UNAVAILABLE", message: "无法获取电池电量", details: nil))
} else {
result(Int(batteryLevel * 100))
}
}
private func showToast(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
alert.dismiss(animated: true)
}
}
}
その他の拡張プラットフォームチャネルは、Flutter とネイティブコードが通信する主要な方法であり、システム API やハードウェア機能の呼び出し、サードパーティ製ネイティブ SDK の使用によく使われます。