flutter-native
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNative Platform Interoperability
原生平台互操作性
Developing Flutter apps often requires direct communication with the underlying native platform (Android/iOS). This skill covers the standards for maintainable and type-safe interoperability.
开发Flutter应用通常需要与底层原生平台(Android/iOS)直接通信。本技能涵盖可维护、类型安全的互操作规范。
1. MethodChannels (One-shot)
1. MethodChannels(单次调用)
Use for standard request-response patterns between Dart and Native.
MethodChannel使用实现Dart与原生端之间的标准请求-响应模式。
MethodChannelDart Standard
Dart规范
- Use a unique domain-style channel name.
- ALWAYS wrap calls in a try-catch for .
PlatformException
dart
static const _channel = MethodChannel('com.example.app/device_info');
Future<String?> getDeviceOS() async {
try {
return await _channel.invokeMethod<String>('getOS');
} on PlatformException catch (e) {
AppLogger.error('Failed to get OS', error: e);
return null;
}
}- 使用唯一的域名风格的通道名称。
- 务必将调用包裹在try-catch中以捕获。
PlatformException
dart
static const _channel = MethodChannel('com.example.app/device_info');
Future<String?> getDeviceOS() async {
try {
return await _channel.invokeMethod<String>('getOS');
} on PlatformException catch (e) {
AppLogger.error('Failed to get OS', error: e);
return null;
}
}2. EventChannels (Streams)
2. EventChannels(流)
Use for continuous data flow (e.g., sensor data, connectivity).
EventChannel使用处理持续数据流(例如传感器数据、网络连接状态)。
EventChannelImplementation
实现要求
- Native side MUST handle and
onListen.onCancel - Dart side MUST dispose the subscription to prevent leaks.
- 原生端必须实现和
onListen处理逻辑。onCancel - Dart端必须销毁订阅以避免内存泄漏。
3. Type Safety with Pigeon
3. 使用Pigeon实现类型安全
For complex APIs, avoid manual string-based keys. Use Pigeon to generate type-safe interfaces.
对于复杂API,避免使用手动编写的字符串键。请使用Pigeon生成类型安全的接口。
4. Platform-Specific Directory Structure
4. 平台专属目录结构
Organize native code within the relevant feature if possible, or use a dedicated directory for shared logic.
plugins/尽可能将原生代码组织到对应功能模块下,或使用专门的目录存放共享逻辑。
plugins/5. Federated Plugins
5. 联合插件
If the logic is reusable across multiple apps:
- Split implementation into ,
_platform_interface,_android, and_iospackages._web - Provide a single entry point for users.
如果相关逻辑可在多个应用间复用:
- 将实现拆分为、
_platform_interface、_android和_ios包。_web - 为使用者提供统一的入口点。