Sub topic 10
Supported types and what Pigeon cannot express
This chapter assumes you can read a Pigeon input file, run the generator, and implement a generated HostApi in Kotlin or Swift. It covers the types that can cross the boundary, what changes on the native side, and the designs Pigeon cannot express. It also covers the usual workarounds.
Why the type list is short
Pigeon generates code on top of the platform channel StandardMessageCodec. That codec serializes a fixed set of values into bytes on one side and rebuilds them on the other. Pigeon adds generated code for your classes and enums, but it does not add new wire types. Anything that cannot be written to that format has no way across the channel.
This is why the type list is short. Both sides need an exact, lossless mapping for every type, in every language Pigeon targets.
Details change between Pigeon releases. Treat this chapter as the working model and check the Pigeon README for the version you pinned.
Types you can use
The table shows how the core types map on each platform.
| Dart | Kotlin | Swift |
|---|---|---|
| `bool` | `Boolean` | `Bool` |
| `int` | `Long` | `Int64` |
| `double` | `Double` | `Double` |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` |
| `Int32List` | `IntArray` | `FlutterStandardTypedData` |
| `Int64List` | `LongArray` | `FlutterStandardTypedData` |
| `Float64List` | `DoubleArray` | `FlutterStandardTypedData` |
| `List` | `List<Any?>` | `[Any?]` |
| `Map` | `Map<Any?, Any?>` | `[AnyHashable?: Any?]` |
| your `enum` | generated `enum class` | generated `enum` |
| your class | generated `data class` | generated `struct` |
Any of these can be made nullable with ?, and nullability is carried into the Kotlin and Swift signatures. Newer Pigeon versions also support Float32List. Check your version before relying on it.
Collections and their element types
Write element types on collections, for example List<String?> or Map<String?, int?>. Pigeon then generates code that casts elements on the native side. A bare List gives you List<Any?> and puts the casting in your hands.
Pigeon has historically required collection element types to be nullable, because the generated native code treats elements as Any?. If the generator rejects List<String>, change it to List<String?>. Then decide how to handle a null element on the Dart side. Newer releases relax this, so confirm with your version.
You can use Object as an element type to say "any supported value", as in List<Object?>. This gives up type safety for that field. Use it only when the data really is heterogeneous.
Data classes
A data class is a plain Dart class with fields and a constructor. Pigeon turns it into a Kotlin data class and a Swift struct. The rules that matter:
- Fields hold supported types, other data classes, or enums.
- Classes can be nested, but a reference cycle between classes may not generate correctly in every language, so keep the graph a tree.
- Fields are copied across the boundary. Native code does not receive a reference to the Dart object.
- Methods, getters, and private state in your input class do not survive. Only the fields are generated.
Enums
Enums cross the boundary as their index. This has a consequence: the order of the values is part of the contract. Appending a value at the end is safe when Dart and native code ship together. Inserting or reordering values in the middle changes the meaning of existing values if the two sides are built from different generations.
Pigeon enums are plain value lists. Enhanced enums with fields or methods do not carry that extra data across.
Platform differences to watch
Dart int is 64-bit on native
Dart int becomes Long in Kotlin and Int64 in Swift. A frequent early bug is writing level as an Int on the Kotlin side. The generated interface expects Long, so the compiler rejects it. The fix is to convert at the edge, as the battery example did with level.toLong().
On Flutter web, Dart int is a JavaScript number. Values above 2^53 lose precision. Pigeon does not generate web-side channel code, so this limit matters only if you share the same Dart int fields with a web build through another route.
Typed lists become different native types
Uint8List is a ByteArray in Kotlin but a FlutterStandardTypedData in Swift. Swift code reads .data to get a Data value. Generated code wraps this for you at the class boundary, but if you handle typed lists inside List<Object?>, you must unwrap them yourself.
Large binary payloads are copied at least once in each direction. For multi-megabyte images or files, pass a file path or a texture id instead of the bytes.
What Pigeon cannot express
Types with no wire format
These Dart types are not supported as fields, arguments, or return values:
DateTime,Duration,Uri,Color,Size,Offset, and other framework typesnum, since the native types must be exact- Functions and callbacks
StreamandFutureas a field or argument type- Classes you cannot declare in the input file, such as classes from another package
Pigeon reads one input file. Types it uses must be declared there, so you cannot reuse a data class that lives somewhere else in your codebase.
Design features the generator does not offer
- Inheritance and polymorphism. Pigeon data classes are flat. Newer releases add limited sealed-class support, so check your version. Without it, use one class with a discriminating enum plus nullable fields.
- Generic user classes. You cannot write
class Result<T>. - Named parameters and default arguments in API methods. Methods take positional parameters. Wrap a group of options in a data class instead.
- Overloading. Each method needs a unique name.
- Returning streams. A
HostApimethod completes once. Continuous events need aFlutterApiorEventChannelApi. - Passing native objects by reference. You cannot hand Dart a live
BitmaporCLLocationManager. Dart receives copies of data, and any native state stays on the native side behind an id you define.
Shape of the contract
Pigeon describes messages and nothing more. It does not express ordering guarantees, versioning, or lifecycle. If your native object must be created before use, model that with explicit create and dispose methods and an id. The generator will not enforce the order.
Working around the gaps
The usual approach is a thin conversion layer. The Pigeon types are the wire format. Your app code uses richer Dart types. A mapping layer translates between the two, and everything outside that layer stays unaware of Pigeon.
This input file uses only wire-safe types:
// pigeons/sync.dart
import 'dart:typed_data';
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/sync.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Sync.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Sync.g.swift',
))
enum SyncStatus { idle, running, failed }
class SyncRecord {
SyncRecord({
required this.id,
required this.updatedAtMillis,
required this.sourceUrl,
required this.status,
this.tags,
this.payload,
});
int id;
int updatedAtMillis; // DateTime is not supported
String sourceUrl; // Uri is not supported
SyncStatus status;
List<String?>? tags;
Uint8List? payload;
}
@HostApi()
abstract class SyncApi {
List<SyncRecord?> pendingRecords();
}The mapping layer in the app converts to richer types:
import 'src/sync.g.dart';
class PendingItem {
PendingItem({
required this.id,
required this.updatedAt,
required this.source,
required this.tags,
});
final int id;
final DateTime updatedAt;
final Uri source;
final List<String> tags;
}
extension SyncRecordMapping on SyncRecord {
PendingItem toDomain() => PendingItem(
id: id,
updatedAt: DateTime.fromMillisecondsSinceEpoch(
updatedAtMillis,
isUtc: true,
),
source: Uri.parse(sourceUrl),
tags: [for (final tag in tags ?? const <String?>[]) ?tag],
);
}
Future<List<PendingItem>> loadPending() async {
final records = await SyncApi().pendingRecords();
return [
for (final record in records)
if (record != null) record.toDomain(),
];
}The ?tag entry in the list literal is Dart's null-aware element syntax, which needs Dart 3.8 or later. On older SDKs, write if (tag != null) tag. The List<SyncRecord?> return type shows the nullable element rule at work: the mapping layer filters out null entries once, at the boundary.
Choosing whether Pigeon fits
Use this decision flow before you commit a design to Pigeon.
Pigeon fits well for request and response calls with structured, copyable data. It fits poorly when:
- Dart must hold live references to native objects.
- You move large binary payloads often.
- The API uses deep type hierarchies that you cannot flatten.
- You need to call C or C++ directly, where FFI is the better tool.
Failure modes to expect
- Generator error on an unsupported type. The message names the field or method. Replace the type with a wire-safe one and add a conversion.
- Stale generated code. If you change the input file and skip regeneration, Dart and native code disagree. The result is a runtime cast error or a missing handler, not a compile error. Regenerate and rebuild all platforms.
- Silent enum shift. Reordering enum values keeps compiling and changes behavior. Only append new values.
ClassCastExceptionor a Swift cast failure at runtime. This usually comes from an untypedListorMapholding something other than what the native code expects. Add element types.
Exercise
A teammate wants a Pigeon method Future<void> schedule(DateTime when, {bool exact = false}). List the changes needed to make it expressible, and state where the conversion from DateTime should live.
Show answer
DateTime is not a supported type, so send an int of UTC milliseconds since the epoch. Named parameters and defaults are not supported, so make the parameters positional (int whenMillis, bool exact) or group them in a data class such as ScheduleRequest. Declare the method as async on the HostApi. The DateTime to int conversion should live in a thin Dart mapping layer outside the generated code, so the rest of the app keeps using DateTime.
Exercise
You add a new value to the middle of a Pigeon enum Mode { off, low, high } so it becomes Mode { off, low, medium, high }. The Dart app is updated but a cached native build is not. What goes wrong, and how do you avoid it?
Show answer
Enums cross the boundary as their index. The old native build reads index 2 as high, but the new Dart code now means medium by 2. The code still compiles and runs, but behavior is wrong. Append medium at the end instead of inserting it, and regenerate and rebuild both platforms together.