Sub topic 4
Describing data: classes, enums and nullable fields
This chapter assumes you have already installed Pigeon and run the generator, as covered in the previous chapter. You should be comfortable reading Dart class definitions and know the basics of Kotlin and Swift types. Here you will learn how to describe the data that crosses the boundary between Dart and native code. Declaring a HostApi comes in the next chapter.
Why the schema is the contract
A Pigeon input file declares the shapes of the messages that cross the platform boundary. Pigeon reads these declarations and writes a matching type on each platform, along with the code that converts the type to and from bytes.
This replaces the hand-written approach, where you pass a Map<String, dynamic> through a MethodChannel and cast each value on the other side. A misspelled key, or a String where an int was expected, only fails at runtime. With a schema, the same mistake is a compile error on the side that uses the generated class.
The schema defines three kinds of building blocks:
- Data classes, which group named fields.
- Enums, which name a closed set of values.
- Nullability, which says whether a field or value may be absent.
Data classes
A data class is a plain Dart class in the input file. Pigeon reads its fields and ignores everything else, so keep it simple: fields and a constructor.
// pigeons/messages.dart
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Messages.g.swift',
))
enum BatteryState { charging, discharging, full, unknown }
class BatteryInfo {
BatteryInfo({
required this.level,
required this.state,
this.temperatureCelsius,
this.chargerName,
});
int level;
BatteryState state;
double? temperatureCelsius;
String? chargerName;
}
class DeviceReport {
DeviceReport({required this.battery, required this.tags});
BatteryInfo battery;
List<String?> tags;
}
@HostApi()
abstract class BatteryApi {
DeviceReport getReport();
}The @ConfigurePigeon annotation is attached to the first declaration in the file, here the BatteryState enum. Pigeon reads the annotation from the file, so its position only needs to be consistent.
Note the getReport method at the end. Pigeon only generates classes that are reachable from an API, so a data class that no API method uses is left out of the output. If a class you defined is missing from messages.g.kt, check that an API method uses it as a parameter or return type.
What the generator writes for each platform
Dart int becomes Long in Kotlin and Int64 in Swift, because Dart integers are 64-bit. Dart double becomes Double. String and bool map to the obvious types. The generated Kotlin class looks roughly like this (abridged):
data class BatteryInfo(
val level: Long,
val state: BatteryState,
val temperatureCelsius: Double? = null,
val chargerName: String? = null
) {
// fromList(...) and toList() are generated here
}The Swift side is a struct with the same fields, where optional fields use Int64?, Double? and so on. Generated code is written in each language's own style, so you read and construct these types the way you would any other Kotlin data class or Swift struct.
The generated Kotlin and Swift code needs no changes from you. Do not edit *.g.* files, because the next run of the generator overwrites them.
How a class is sent
Each data class is encoded as a list of its field values in declaration order, and the receiving side rebuilds the object from that list. Field names never travel over the channel. This has two consequences:
- Both sides must be generated from the same schema version. A Dart app built from one schema and a native library built from another can decode values into the wrong fields.
- Reordering fields in the schema changes the wire format. That is harmless when you regenerate everything together, as in an app. It matters if a plugin and its host app are built and released separately.
Nullable fields
Nullability in the schema is the same as in Dart. A field typed int is non-null, and a field typed int? may be absent.
| Dart field | Kotlin field | Swift field |
|---|---|---|
| `int level` | `val level: Long` | `var level: Int64` |
| `double? temperatureCelsius` | `val temperatureCelsius: Double?` | `var temperatureCelsius: Double?` |
| `String? chargerName` | `val chargerName: String?` | `var chargerName: String?` |
| `BatteryState state` | `val state: BatteryState` | `var state: BatteryState` |
Nullability is enforced at both ends. The generated decoding code treats a non-null field as required. If native code could not produce a value, for example a temperature sensor that does not exist on some devices, declare the field nullable up front. Otherwise you would need to invent a sentinel value such as -1, and every caller would have to remember to check for it.
When you construct a class on the native side, the nullable parameters have defaults, so you can leave them out:
val info = BatteryInfo(level = 80L, state = BatteryState.CHARGING)let info = BatteryInfo(level: 80, state: .charging)The Swift struct's initializer also has defaults for optional fields, so both calls above are valid and set the optional fields to nil.
Enums
An enum in the schema is a plain Dart enum with no fields or methods. Pigeon generates the equivalent on each platform:
- In Dart, you get the same
enum, soinfo.state.nameworks as in the earlier chapters' calling code. - In Kotlin, you get an
enum class. The constant names are converted to upper case, sounknownbecomesUNKNOWN. - In Swift, you get an
enumwith the original lower camel case names, such as.unknown.
The case conversion is why the Kotlin example in the spine writes BatteryState.UNKNOWN, while the Swift one writes .unknown.
Enums travel as integer indexes
On the wire, an enum value is sent as its index in the declaration. So:
- Adding a new value at the end of the enum is the safest change.
- Inserting a value in the middle shifts the indexes of every later value.
- Removing or reordering values changes the meaning of the integers that older code sends.
For an app that you rebuild as a whole, none of this is a problem. It becomes a concern when two versions of the code can talk to each other, for example a plugin whose Dart and native halves are updated independently.
Enums can be used as fields in data classes, as shown with state. They can also be used directly as method arguments and return values in an API. Because the integer decoding needs a valid index, an unknown number from a mismatched version fails at decode time instead of silently turning into the wrong state.
Nested classes and collections
A data class can contain another data class, as DeviceReport contains BatteryInfo. Pigeon generates both classes and handles the nesting during encoding. A nested class field can be nullable too (BatteryInfo? battery).
Collections are limited to the types Pigeon knows. Pigeon supports List and Map fields, and the typed lists such as Uint8List for binary data. Write the element types explicitly. Pigeon expects nullable element types in collections, such as List<String?> and Map<String?, int?>, because the underlying codec can carry a null element. The exact rule depends on the Pigeon version, so check the generator's output or error message if a collection field is rejected.
The next table summarizes the field types you will use most often.
| Dart type | Kotlin type | Swift type |
|---|---|---|
| `bool` | `Boolean` | `Bool` |
| `int` | `Long` | `Int64` |
| `double` | `Double` | `Double` |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` |
| `List<T?>` | `List<T?>` | `[T?]` |
| `Map<K?, V?>` | `Map<K?, V?>` | `[K?: V?]` |
A later chapter covers the full list of supported types and what Pigeon cannot express. For now, keep your classes made of the types above and of other classes and enums from the same file.
Common mistakes
These are the errors you are most likely to meet when you write a schema.
- Expecting methods on data classes. Only fields are generated. If you add a helper method, it will exist in your input file and nowhere else. Put the logic in a separate Dart extension on the generated class instead.
- Using inheritance between data classes. A data class that extends another one is not a supported shape for plain classes, so use composition. Hold one class inside another, as
DeviceReportdoes. - Using types from other packages. A field typed
DateTimeorDurationis not on the supported list. Send anintof milliseconds or aStringin ISO 8601 form, and convert in Dart. - Forgetting to regenerate. After you change a field, rerun
dart run pigeon --input pigeons/messages.dart. The Kotlin and Swift code stops compiling until the native implementation matches the new schema, which is the compile-time safety you wanted. - Treating
intas 32-bit. Kotlin seesLongand Swift seesInt64. If you call a platform API that returns anInt, convert it with.toLong()in Kotlin orInt64(...)in Swift, as the battery examples do.
Putting the schema to use
Once you regenerate, the Dart side can build and read these values directly:
import 'src/messages.g.dart';
String describe(BatteryInfo info) {
final temperature = info.temperatureCelsius;
final temperatureText =
temperature == null ? 'unknown temperature' : '$temperature °C';
return '${info.level}% ${info.state.name}, $temperatureText';
}
void main() {
print(describe(BatteryInfo(level: 80, state: BatteryState.charging)));
print(describe(BatteryInfo(
level: 15,
state: BatteryState.discharging,
temperatureCelsius: 31.5,
)));
}Dart's flow analysis requires the local temperature variable here. A nullable field on a class cannot be promoted to non-null by a null check, because another part of the program could change it between the check and the use.
Exercise
Your schema has enum ChargerType { usb, wireless, none }, and a released app version already sends these values to native code. You want to add solar. Where should you put it, and why? Also, what Kotlin name will the constant have?
Show answer
Add it at the end: enum ChargerType { usb, wireless, none, solar }. Enums are sent as their integer index, so appending keeps usb, wireless and none at 0, 1 and 2, while inserting solar earlier would shift the later indexes and change what older code means. In Kotlin the constant is ChargerType.SOLAR, because Pigeon converts the names to upper case there. In Swift it is .solar.
Exercise
A sensor reading is missing on some devices. Which is the better schema field for it, double temperatureCelsius with -1 meaning "missing", or double? temperatureCelsius? Name one concrete benefit of your choice.
Show answer
Use double? temperatureCelsius. A missing value is sent as null and arrives as null in Dart, null in Kotlin and nil in Swift, so each language's own null checks apply. With the -1 sentinel, every caller must remember the special value, and a real reading could be mistaken for it or the sentinel might be shown to a user.