Flutter에서 MethodChannel은 Flutter와 네이티브 플랫폼(Android, iOS) 간에 데이터와 메서드를 주고받는 데 사용됩니다. 이를 통해 Flutter 앱 내에서 네이티브 코드(예: Java, Kotlin, Objective-C, Swift)와 상호작용할 수 있습니다. MethodChannel을 사용하면 Flutter와 네이티브 간에 기능을 확장하거나 네이티브 API를 활용할 수 있습니다.
1. MethodChannel이란?
- MethodChannel은 Flutter와 네이티브 플랫폼 간에 메서드 호출과 결과를 전달하는 채널입니다.
- Flutter에서는 MethodChannel을 사용하여 네이티브 코드에 메서드를 호출하거나 네이티브 코드에서 결과를 Flutter로 반환할 수 있습니다.
2. Flutter에서 MethodChannel 사용하기
2.1. Flutter 코드에서 MethodChannel 설정
Flutter 앱에서 MethodChannel을 설정하여 네이티브 코드와 통신할 수 있습니다. MethodChannel 객체를 생성한 후, 해당 채널을 통해 메서드 호출을 할 수 있습니다.
(본인은 ViewModel의 notifier에 객체를 생성합니다.)
import 'package:flutter/services.dart';
class MyMethodChannel {
static const platform = MethodChannel('com.example/mychannel'); // 채널 이름 설정
// 네이티브 메서드 호출
Future<void> callNativeMethod() async {
try {
final result = await platform.invokeMethod('myMethod', {'param': 'value'});
print(result);
} on PlatformException catch (e) {
print("Failed to invoke method: '${e.message}'.");
}
}
}
- MethodChannel은 첫 번째 인자로 채널 이름을 받음
- invokeMethod를 사용하여 네이티브 메서드를 호출
- 네이티브 코드에서 메서드 호출 후 결과를 반환
2.2. 네이티브 코드에서 메서드 처리
Android (Kotlin):
package com.example.myapp
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example/mychannel"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MethodChannel(flutterEngine?.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "myMethod") {
val param = call.argument<String>("param")
result.success("Received param: $param")
} else {
result.notImplemented()
}
}
}
}
- 네이티브 코드에서 setMethodCallHandler로 메서드 호출을 처리
- 호출된 메서드가 존재하면 결과를 result.success()로 반환하거나, 구현되지 않은 메서드일 경우 result.notImplemented()로 처리
3. 주요 메서드
- invokeMethod(String method, [arguments]): Flutter에서 네이티브 메서드를 호출
- setMethodCallHandler(MethodCallHandler callback): 네이티브 코드에서 메서드 호출을 처리하는 핸들러를 설정
4. 에러 처리
Flutter와 네이티브 코드 간의 통신 중 오류가 발생할 수 있습니다. PlatformException을 사용하여 오류를 처리할 수 있습니다.
try {
final result = await platform.invokeMethod('myMethod');
print(result);
} on PlatformException catch (e) {
print("Error: ${e.message}");
}
5. 예시: 간단한 MethodChannel 예제
5.1. Flutter 코드
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const platform = MethodChannel('com.example/mychannel');
Future<void> _callNativeMethod() async {
try {
final result = await platform.invokeMethod('getPlatformVersion');
print(result);
} on PlatformException catch (e) {
print("Failed to invoke: ${e.message}");
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("MethodChannel Example")),
body: Center(
child: ElevatedButton(
onPressed: _callNativeMethod,
child: Text("Call Native Method"),
),
),
),
);
}
}
5.2. Android (Kotlin)
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example/mychannel"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MethodChannel(flutterEngine?.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getPlatformVersion") {
val version = "Android ${android.os.Build.VERSION.RELEASE}"
result.success(version)
} else {
result.notImplemented()
}
}
}
}
결론
Flutter의 MethodChannel은 Flutter와 네이티브 코드 간의 메서드 호출 및 데이터를 교환하는 강력한 도구입니다. 이를 사용하여 네이티브 플랫폼의 기능을 Flutter 앱에 통합할 수 있습니다. Flutter에서는 MethodChannel을 사용하여 네이티브 코드의 메서드를 호출하고, 네이티브 코드에서는 해당 메서드를 처리하여 결과를 Flutter로 반환하는 방식으로 동작합니다.
이 방법을 통해 플랫폼 독립적인 Flutter 애플리케이션에서 네이티브 기능을 활용할 수 있습니다.
'개발 > Android' 카테고리의 다른 글
[Flutter] Riverpod 상태관리 - ConsumerStatefulWidget 가이드 (0) | 2025.04.02 |
---|---|
[Flutter] Riverpod 상태관리 - watch vs read 차이 (0) | 2025.04.02 |
[Flutter] Riverpod 상태관리 - ConsumerWidget 가이드 (0) | 2025.04.02 |
[Flutter] 간단한 ToDo앱에서 MethodChannel 응용 (0) | 2025.03.10 |
[Flutter] Riverpod 상태관리 라이브러리 (0) | 2025.02.20 |