0Pricing
Flutter Mobile Development · 강의

iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성

네이티브 Kotlin 및 Swift API를 Dart에 노출하는 연합 플러그인을 작성합니다.

iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Platform Plugins?

Dart cannot call native iOS or Android APIs directly. A platform plugin bridges that gap, exposing Swift/Objective-C and Kotlin/Java capabilities to your Dart code through a typed channel.

  • Package: pure Dart, no native code.
  • Plugin: Dart API plus platform-specific native implementations.

You write a plugin whenever you need hardware (sensors, BLE), OS services (notifications, keychain), or a native SDK that has no Dart equivalent. In this lesson we author a federated plugin that surfaces native Kotlin and Swift APIs to Dart.

Federated Plugin Architecture

A federated plugin splits responsibilities across several packages so different parties can own different platforms:

  • app-facing package (battery): the public Dart API developers import.
  • platform interface (battery_platform_interface): an abstract contract all implementations must satisfy.
  • platform packages (battery_android, battery_ios): concrete native implementations registered via pubspec.yaml.

This decoupling lets a third party add, say, a Windows implementation without touching the app-facing package. The interface package is the linchpin contract.

The Platform Interface Contract

The platform interface uses the plugin_platform_interface package. It declares an abstract base class with a MethodChannel-free contract, plus a default instance other packages override.

The PlatformInterface token-verification prevents implementers from extends-ing and breaking the contract; they must use implements guarded by verifyToken.

import 'package:plugin_platform_interface/plugin_platform_interface.dart';

abstract class BatteryPlatform extends PlatformInterface {
  BatteryPlatform() : super(token: _token);

  static final Object _token = Object();
  static BatteryPlatform _instance = MethodChannelBattery();

  static BatteryPlatform get instance => _instance;

  static set instance(BatteryPlatform value) {
    PlatformInterface.verifyToken(value, _token);
    _instance = value;
  }

  Future<int> getBatteryLevel() {
    throw UnimplementedError('getBatteryLevel() is not implemented.');
  }
}

MethodChannel: The Default Implementation

The default implementation talks to native code over a MethodChannel. Each channel has a unique name shared by Dart and native sides. invokeMethod serializes arguments using the standard message codec and awaits a native reply.

Keep channel names namespaced (reverse-DNS) to avoid collisions across plugins.

import 'package:flutter/services.dart';
import 'battery_platform_interface.dart';

class MethodChannelBattery extends BatteryPlatform {
  final MethodChannel _channel =
      const MethodChannel('com.example.battery/methods');

  @override
  Future<int> getBatteryLevel() async {
    final level = await _channel.invokeMethod<int>('getBatteryLevel');
    if (level == null) {
      throw PlatformException(code: 'NO_LEVEL', message: 'Level unavailable');
    }
    return level;
  }
}

Android: Kotlin Plugin Registration

On Android the native side implements FlutterPlugin and MethodChannel.MethodCallHandler. In onAttachedToEngine you wire a MethodChannel with the same name used in Dart, then route incoming calls in onMethodCall.

  • result.success(value) resolves the Dart Future.
  • result.error(code, msg, details) throws a PlatformException in Dart.
  • result.notImplemented() signals an unknown method.

This is Kotlin, not Dart, so it is illustrative only.

iOS: Swift Plugin Registration

On iOS you conform to FlutterPlugin and register in register(with:), creating a FlutterMethodChannel with the matching name. handle(_:result:) dispatches calls and replies via the FlutterResult callback.

For federated plugins the platform package declares its native entry point under flutter.plugin.platforms.ios in pubspec.yaml, pointing at the Swift class. The Dart registrant is wired automatically.

Declaring the Federated pubspec

The platform implementation packages announce themselves via flutter.plugin.platforms. The dartPluginClass is registered with the platform interface at startup, and pluginClass names the native class.

Crucially the app-facing package lists each platform package under default_package, so adding a platform is a pubspec change, not a code change.

Endorsing Platform Implementations

The app-facing package endorses implementations by depending on them in its pubspec.yaml. Endorsed packages are pulled in transitively, so app developers add one dependency and get every platform.

At runtime, each platform package's registerWith() sets the interface's instance to its own implementation. The Dart API then calls through BatteryPlatform.instance without knowing which platform answered.

// battery_android registers itself at startup
import 'battery_platform_interface.dart';

class BatteryAndroid extends BatteryPlatform {
  /// Registered via dartPluginClass in pubspec.yaml.
  static void registerWith() {
    BatteryPlatform.instance = BatteryAndroid();
  }

  @override
  Future<int> getBatteryLevel() {
    // Delegates to the MethodChannel under the hood.
    return MethodChannelBattery().getBatteryLevel();
  }
}

The App-Facing Dart API

The public package wraps the interface in an ergonomic, well-documented API. App developers never touch channels or platform classes — they call clean Dart methods.

Keep this layer thin: validation, convenience overloads, and documentation. All real work lives behind BatteryPlatform.instance.

import 'battery_platform_interface.dart';

class Battery {
  /// Returns the current battery level as a percentage (0-100).
  Future<int> get batteryLevel => BatteryPlatform.instance.getBatteryLevel();

  /// Convenience: true when the device is critically low.
  Future<bool> get isCritical async => (await batteryLevel) <= 15;
}

Streaming Native Events with EventChannel

For continuous data (charging state, sensor streams) a single method call is not enough. Use an EventChannel: the native side pushes events through a StreamHandler/FlutterEventSink, and Dart exposes them as a Stream.

receiveBroadcastStream lazily starts the native listener on first subscription and tears it down on cancel.

import 'package:flutter/services.dart';

class BatteryStream {
  final EventChannel _events =
      const EventChannel('com.example.battery/charging');

  Stream<bool> get onChargingChanged => _events
      .receiveBroadcastStream()
      .map((event) => event == 'charging');
}

Type-Safe Channels with Pigeon

Hand-written channels are stringly-typed and error-prone. Pigeon generates type-safe Dart, Kotlin, and Swift bindings from a single Dart definition file, eliminating method-name typos and codec mismatches.

You annotate an abstract class with @HostApi() (Dart calls native) or @FlutterApi() (native calls Dart), run the Pigeon generator, and wire the generated classes — no manual invokeMethod strings.

import 'package:pigeon/pigeon.dart';

class BatteryInfo {
  int? level;
  bool? isCharging;
}

@HostApi()
abstract class BatteryHostApi {
  BatteryInfo getBatteryInfo();
}

@FlutterApi()
abstract class BatteryFlutterApi {
  void onLevelChanged(int level);
}

Quick Check

You are publishing a Flutter plugin and want third parties to add new platform implementations (e.g. Windows) without modifying or forking your app-facing package. Which architecture and mechanism makes that possible?

Recap

You learned to author a federated platform plugin exposing native Kotlin and Swift APIs to Dart:

  • Architecture: app-facing package, platform interface, and per-platform implementations.
  • Contract: an abstract PlatformInterface with token verification and a swappable instance.
  • Channels: MethodChannel for request/response, EventChannel for native event streams, with matching names on both sides.
  • Native sides: Kotlin onMethodCall and Swift handle(_:result:) resolving via success/error.
  • Endorsement: pubspec wires dartPluginClass and pluginClass so platforms register themselves.
  • Pigeon: generates type-safe bindings to replace fragile string-based channels.

With this you can wrap any native SDK behind a clean, testable Dart API.

자주 묻는 질문

“iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성” 강의는 무료인가요?

네 — “iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성”에서 뭘 배우나요?

네이티브 Kotlin 및 Swift API를 Dart에 노출하는 연합 플러그인을 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. dart:ffi로 C 라이브러리 호출하기
  2. Pigeon을 활용한 타입 안전 플랫폼 채널
  3. iOS 및 Android용 사용자 지정 플랫폼 플러그인 작성
  4. 백그라운드 아이솔레이트 및 네이티브 메모리 관리
← Flutter Mobile Development(으)로 돌아가기