flutter-plugins은(는) 무엇을 하나요?
다른 Flutter 앱에서 사용할 수 있도록 네이티브 상호 운용성을 제공하는 Flutter 플러그인을 만듭니다.
개요
Flutter 플러그인은 Dart 코드와 네이티브 플랫폼 코드(Android의 경우 Java/Kotlin, iOS의 경우 Objective-C/Swift) 간의 브리지 역할을 합니다. 이 스킬은 플랫폼별 기능을 노출하는 플러그인을 구축하고 패키지화하는 과정을 안내합니다.
설정
-
새 플러그인 프로젝트 만들기
flutter create --org com.example --template=plugin hello_plugin cd hello_plugin -
플러그인 구조 이해하기
lib/– Dart API (hello_plugin.dart)android/– Android 네이티브 구현ios/– iOS 네이티브 구현example/– 플러그인을 사용하는 테스트 Flutter 앱
네이티브 메서드 구현
Dart 쪽 (lib/hello_plugin.dart)
import 'dart:async';
import 'package:flutter/services.dart';
class HelloPlugin {
static const MethodChannel _channel = MethodChannel('hello_plugin');
static Future<String?> get platformVersion async {
final String? version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
}
Android 쪽 (android/src/main/kotlin/com/example/hello_plugin/HelloPlugin.kt)
package com.example.hello_plugin
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class HelloPlugin: FlutterPlugin, MethodChannel.MethodCallHandler {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
val channel = MethodChannel(binding.binaryMessenger, "hello_plugin")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {}
}
iOS 쪽 (ios/Classes/HelloPlugin.m)
#import "HelloPlugin.h"
#if __has_include(<hello_plugin/hello_plugin-Swift.h>)
#import <hello_plugin/hello_plugin-Swift.h>
#endif
@implementation HelloPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftHelloPlugin registerWithRegistrar:registrar];
}
@end
Swift 파일 (ios/Classes/HelloPlugin.swift)
import Flutter
import UIKit
public class SwiftHelloPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "hello_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftHelloPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getPlatformVersion" {
result("iOS " + UIDevice.current.systemVersion)
} else {
result(FlutterMethodNotImplemented)
}
}
}
메서드 채널 이해하기
- MethodChannel은 네이티브 코드와 DART 코드가 문자열 이름을 통해 메서드를 호출할 수 있게 해줍니다.
- 플러그인은 binaryMessenger를 통해 등록되며, 이는 엔진이 연결될 때 자동으로 제공됩니다.
- 채널 이름은 Dart와 네이티브 쪽에서 동일해야 합니다.
패키징 및 배포
-
pubspec.yaml 업데이트
name: hello_plugin version: 0.0.1 description: A new Flutter plugin. environment: sdk: ">=2.12.0 <3.0.0" -
플러그인 게시 (
pub.dev필요)flutter pub publish
리소스
- Flutter 플러그인 개발 문서
- pub.dev – Flutter 패키지 저장소
- MethodChannel API