Flutter의 네이티브 코드 호출 방법
Flutter는 Android(Java/Kotlin), iOS(Swift/Object-C)와 같은 네이티브 코드를 호출하여 플랫폼별 기능을 활용할 수 있도록 플랫폼 채널(Platform Channel)을 제공합니다. 이를 통해 네이티브 API를 사용하여 카메라, GPS, 파일 시스템 등 Flutter에서 직접 접근할 수 없는 기능을 활용할 수 있습니다.
이 글에서는 Flutter에서 네이티브(Android 및 iOS) 코드를 호출하는 방법을 MethodChannel을 활용하여 구현하는 방법을 알아보겠습니다.
1. 네이티브 코드 호출이 필요한 이유
Flutter는 크로스플랫폼 UI 프레임워크이지만, 일부 기능은 네이티브 코드(Android, iOS)에서만 사용할 수 있습니다.
예를 들어, 다음과 같은 기능은 네이티브 API 호출이 필요합니다.
- 카메라, 갤러리 접근
- GPS 및 센서 데이터 활용
- 네이티브 UI 구성 요소 사용
- 플랫폼별 설정 정보 가져오기
- 백그라운드 서비스 실행
이제 Flutter에서 네이티브 기능을 호출하는 방법을 단계별로 살펴보겠습니다.
2. 플랫폼 채널(Platform Channel) 개념
Flutter에서 네이티브 코드를 호출하는 기본적인 방법은 MethodChannel을 사용하는 것입니다.
- Flutter → 네이티브: Flutter에서 네이티브 메서드를 호출
- 네이티브 → Flutter: 네이티브에서 Flutter로 데이터 전달
플랫폼 채널을 사용하면 Flutter와 네이티브 코드가 JSON 형식의 메시지를 주고받을 수 있습니다.
3. Flutter에서 네이티브 메서드 호출
먼저, Flutter에서 네이티브 코드를 호출하는 MethodChannel을 설정합니다.
(1) Flutter에서 네이티브 채널 설정
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: NativeMethodExample(),
);
}
}
class NativeMethodExample extends StatefulWidget {
@override
_NativeMethodExampleState createState() => _NativeMethodExampleState();
}
class _NativeMethodExampleState extends State {
static const platform = MethodChannel('com.example/native');
String _nativeMessage = '네이티브 메시지를 가져오는 중...';
Future getNativeMessage() async {
try {
final String result = await platform.invokeMethod('getMessage');
setState(() {
_nativeMessage = result;
});
} on PlatformException catch (e) {
setState(() {
_nativeMessage = "네이티브 호출 실패: ${e.message}";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('플랫폼 채널 예제')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_nativeMessage, style: TextStyle(fontSize: 18)),
SizedBox(height: 20),
ElevatedButton(
onPressed: getNativeMessage,
child: Text('네이티브 메시지 가져오기'),
),
],
),
),
);
}
}
이제 Flutter에서 MethodChannel을 통해 getMessage 메서드를 호출하고, 네이티브 코드에서 응답을 받을 준비가 되었습니다.
4. Android에서 네이티브 코드 작성
Android에서 Flutter의 네이티브 요청을 처리하려면 MethodChannel을 구현해야 합니다.
(1) Kotlin(Java도 가능)으로 네이티브 메서드 추가
android/app/src/main/kotlin/com/example/MainActivity.kt 파일을 수정합니다.
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example/native"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getMessage") {
result.success("Android 네이티브 메시지")
} else {
result.notImplemented()
}
}
}
}
이제 Android에서 getMessage를 호출하면 "Android 네이티브 메시지"가 반환됩니다.
5. iOS에서 네이티브 코드 작성
iOS에서는 Swift로 MethodChannel을 구현해야 합니다.
(1) Swift에서 네이티브 메서드 추가
ios/Runner/AppDelegate.swift 파일을 수정합니다.
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(name: "com.example/native", binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { (call, result) in
if call.method == "getMessage" {
result("iOS 네이티브 메시지")
} else {
result(FlutterMethodNotImplemented)
}
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
이제 iOS에서 getMessage를 호출하면 "iOS 네이티브 메시지"가 반환됩니다.
6. 실행 및 테스트
Flutter 앱을 실행하면 Android 및 iOS에서 네이티브 코드를 호출할 수 있습니다.
- Android 실행:
flutter run -d android - iOS 실행:
flutter run -d ios
버튼을 클릭하면 현재 실행 중인 플랫폼(Android 또는 iOS)에 따라 다른 메시지가 출력됩니다.
결론
Flutter에서 네이티브 코드를 호출하는 방법은 다음과 같습니다.
- MethodChannel: Flutter와 네이티브 간 데이터 교환
- Android: Kotlin(Java)에서
MethodChannel을 사용하여 메서드 구현 - iOS: Swift에서
FlutterMethodChannel을 사용하여 메서드 구현
이제 Flutter에서 네이티브 기능을 활용하여 더욱 강력한 앱을 개발해 보세요!
'Flutter' 카테고리의 다른 글
| Flutter의 플랫폼별 UI 차이점 (0) | 2025.03.26 |
|---|---|
| Flutter의 플랫폼 채널(Platform Channel) 사용법 (1) | 2025.03.26 |
| Flutter의 네이티브 플러그인 개발 방법 (0) | 2025.03.25 |
| Flutter의 플러그인 사용법 (0) | 2025.03.25 |
| Flutter의 안드로이드 스타일 위젯(Material Widgets) 사용법 (0) | 2025.03.25 |