tezvyn:

Pigeon: Type-Safe Platform Channels in Flutter

AI-drafted, machine-checkedSource: github.comintermediate

Pigeon acts like a contract for your app's native code, generating type-safe platform channels from a single definition. This replaces manual, error-prone MethodChannel code. The footgun: Swift types default to structs; use `@SwiftClass` for class features.

WHY IT EXISTS Flutter apps often need to talk to native platform APIs, like device sensors or third-party SDKs. The default mechanism, MethodChannel, is string-based and requires manual data serialization. This is error-prone, as a simple typo in a method name or a data type mismatch between Dart and native code can cause runtime failures that are difficult to debug.

THE MENTAL MODEL Think of Pigeon as an Interface Definition Language (IDL) for your app's internal communication. You write a single "contract" file in Dart that defines the functions and data structures. Pigeon then acts as a compiler, taking that contract and generating the type-safe client (Dart) and server (native platform) code, guaranteeing they can talk to each other correctly.

HOW IT WORKS You create a Dart file defining your API within a class annotated with @HostApi. This class contains the method signatures and data types for your communication. After defining the contract, you run the Pigeon command-line tool. It reads this file and outputs a Dart file for your Flutter app and corresponding files for your native platforms (e.g., Swift for iOS, Kotlin for Android). Your app code calls the generated Dart methods, and your native code implements the generated native interfaces.

WHEN TO USE IT Use Pigeon for any non-trivial communication between Flutter and the host platform. It's ideal when you need to call native APIs from Dart or have native code trigger actions in your Flutter app. It eliminates manual serialization and the risk of stringly-typed method call errors, making your code more robust and maintainable.

WHEN NOT TO USE IT For an extremely simple, one-off platform call where the overhead of setting up the generator feels too high, you might still use a manual MethodChannel. However, for any API that will be maintained or expanded, Pigeon is almost always the better and safer choice.

ONE CANONICAL EXAMPLE To get the device's battery level, you'd define a @HostApi() class in your pigeon file with a method like int getBatteryLevel(). After running the generator, you'd get a Dart method getBatteryLevel() to call in your app, and a corresponding native protocol or interface. You would then write the native implementation in Swift or Kotlin that returns the device's battery level as an integer, and Pigeon handles all the plumbing in between.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.