Sub topic 1
Understanding Flutter's Native Platform Boundary
Flutter runs Dart code in its own environment. This gives an app a consistent UI and behavior across Android and iOS. However, some capabilities belong to the operating system. Examples include Bluetooth, biometric authentication, background services, and platform-specific sensors.
A platform boundary is the point where Flutter code communicates with native code. Native code is code written for a specific operating system, such as Kotlin or Java for Android and Swift or Objective-C for iOS. Flutter crosses this boundary through platform channels.
Prerequisites
This chapter assumes intermediate Dart and Flutter experience. You should understand Future, Stream, asynchronous functions, and event handlers. Basic familiarity with either Android Kotlin or iOS Swift is also useful.
The communication model
Dart code sends a message through a named channel. Native code listens on the same channel, performs platform work, and sends a response or event back. The channel does not directly expose native objects to Dart. Instead, both sides exchange values that a message codec can encode and decode.
A codec is a serializer. It converts values into a transferable message and reconstructs them on the other side. Common transferable values include:
null, booleans, numbers, and strings- Lists containing transferable values
- Maps with transferable keys and values
- Byte data, when supported by the codec
The two sides must agree on the channel name, method name, argument shape, and result shape. A spelling difference in a channel name creates two unrelated channels.
Selecting the boundary
Use a MethodChannel when Dart makes a request and expects one result. For example, Dart might request the device battery level. The native handler receives a method name and arguments, then completes the request with a value or error.
Use an EventChannel when native code produces a sequence of updates over time. A sensor reading, location update, or connectivity change is better represented as a Dart Stream. Dart subscribes to the stream, and native code sends events until the subscription is canceled.
| Communication need | Suitable channel | Dart result |
|---|---|---|
| One request and one response | `MethodChannel` | `Future<T>` |
| Ongoing native updates | `EventChannel` | `Stream<T>` |
The boundary is asynchronous. A native operation can take time, and the Dart isolate should not wait synchronously for it. Native handlers must also respect their platform's threading rules and application lifecycle. Those concerns become important when a channel owns resources such as a sensor listener.
Exercise
Which channel should you choose for a native GPS provider that emits location updates while a user is subscribed?
Show answer
Use an EventChannel because the data is an ongoing sequence represented by a Dart Stream.