Sub topic 1
Understanding Flutter's Native Platform Boundary
Prerequisites
You should be comfortable with intermediate Dart and Flutter, Future and async/await, and reading a short Kotlin or Swift function. This chapter does not require writing native code yet.
Where Dart Stops and Native Code Starts
Flutter draws its own user interface and runs your Dart code. Device features such as battery level, sensors, and file pickers belong to the operating system, so they are implemented in native code: Kotlin on Android and Swift on iOS. The boundary is the point where Dart code must hand work to that native code. Platform channels are Flutter's mechanism for crossing it.
How Platform Channels Carry Messages
A platform channel sends a message from Dart to native code, or back again. Each message travels on a named channel. Flutter encodes the message with a codec, passes the bytes across, and decodes them on the other side. Messages are asynchronous, so Dart keeps running while native code works.
Naming Channels and Registering Handlers
A channel name is a string that both sides must match exactly. A reverse-domain style such as com.example.app/battery avoids collisions. The native side registers a handler for that name. Dart sends calls to the name, and the handler receives them.
| Part | Example | Purpose |
|---|---|---|
| Channel name | com.example.app/battery | Routes messages to the right handler |
| Method name | getBatteryLevel | Names the operation to run |
| Arguments | {'includeHistory': true} | Carries input data |
Message Codecs and Values That Cross the Boundary
The standard message codec supports null, bool, int, double, String, Uint8List, List, and Map. Convert custom objects into these types before sending them. A Dart int arrives as an Int or Long on Android, so check the native type when you read it.
Choosing MethodChannel for Request-Response Calls
MethodChannel fits a single request that gets a single reply. Dart calls a named method, and native code returns one result. Use it for actions such as reading the battery level. Continuous updates, such as sensor readings, need EventChannel, which the next chapter covers.
Calling Native Methods from Dart
Create a MethodChannel with the agreed name, then call invokeMethod with the method name.
import 'package:flutter/services.dart';
class BatteryApi {
static const _channel = MethodChannel('com.example.app/battery');
Future<int> getBatteryLevel() async {
final level = await _channel.invokeMethod<int>('getBatteryLevel');
return level ?? -1;
}
}Exercise
Why must the Dart channel name match the native channel name exactly?
Show answer
Flutter routes each message by its channel name string. If the names differ, no native handler receives the call, and Dart throws MissingPluginException.