🔖 หมวดบทเรียน: การเชื่อมต่อกับฟีเจอร์ native ของอุปกรณ์
📌 เหมาะสำหรับ: นักพัฒนาที่ต้องการเข้าถึงเซ็นเซอร์ กล้อง หรือฟังก์ชันเฉพาะของ Android/iOS
🎯 เป้าหมาย: เรียนรู้การสื่อสารระหว่าง Dart กับ Native (Java/Kotlin หรือ Objective-C/Swift)
🧭 เกริ่นนำ
Flutter สามารถสื่อสารกับ native code ได้ผ่านสิ่งที่เรียกว่า Platform Channel ทำให้เราสามารถเรียกใช้ฟังก์ชัน native ได้ เช่น การใช้ Bluetooth, เซ็นเซอร์, API จาก Android/iOS ที่ Flutter ไม่มีให้ตรง ๆ โดยใช้ MethodChannel
เป็นตัวกลาง
⚙️ วิธีสร้าง Platform Channel
1. ฝั่ง Dart (Flutter)
static const platform = MethodChannel('com.example.native/channel');
Future<void> _getBatteryLevel() async {
try {
final int result = await platform.invokeMethod('getBatteryLevel');
print('Battery level: \$result%');
} catch (e) {
print('Failed to get battery level: \$e');
}
}
2. ฝั่ง Android (Kotlin)
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example.native/channel"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
result.success(batteryLevel)
} else {
result.notImplemented()
}
}
}
private fun getBatteryLevel(): Int {
val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager
return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
}
}
🧪 บน iOS (Swift)
let controller = window.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(name: "com.example.native/channel", binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { (call, result) in
if call.method == "getBatteryLevel" {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
result(device.batteryLevel * 100)
} else {
result(FlutterMethodNotImplemented)
}
}
✅ สรุป
- ใช้
MethodChannel
สำหรับสื่อสารข้ามภาษา (Dart ↔ Android/iOS) - รองรับการส่งค่ากลับและจัดการ error ได้
- เหมาะกับการใช้เซ็นเซอร์/ระบบที่ Flutter ยังไม่รองรับตรง
บทถัดไปเราจะไปต่อกับ การใช้งาน Plugin ที่เขียนเอง (Custom Platform Plugin) เพื่อการ reuse และ scale ในระดับ production