跳到正文
教程首页
FlutterCH 15ch15_platform_channels

ch15-platform-channels

平台通道与原生互操作:MethodChannel / EventChannel。完整工程共 100 个文件,其中 60 个文本源文件可在下面在线阅读。

60

在线文本文件

3,832

源码行数

dart / c / yaml

语言

281 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

textxmldartkotlinyaml

60 text files · 3,832 lines

dartlib/src/platform_service.dart
/// 平台通道的 Dart 侧:`MethodChannel`(请求-响应)与 `EventChannel`(事件流)。
///
/// 对照 ch10 的 FFI:
///   FFI        —— 直接按 C ABI 调用,无序列化,适合算法库
///   平台通道   —— 跨语言消息(StandardMessageCodec),适合调 Kotlin/Swift 的系统能力
///
/// 通道名是唯一的契约:Dart 与原生两侧必须写成完全相同的字符串。
library;

import 'package:flutter/services.dart';

/// 与原生约定的通道名(改一处必须改三处:Dart / Android / iOS-macOS)。
const String kDeviceChannel = 'ch15.platform/device';
const String kTicksChannel = 'ch15.platform/ticks';

/// 原生返回的设备信息。
class PlatformInfo {
  const PlatformInfo({
    required this.os,
    required this.version,
    required this.arch,
    this.isDarkMode = false,
  });

  /// 容错解析:原生字段缺失时不崩。
  factory PlatformInfo.fromMap(Map<Object?, Object?> map) => PlatformInfo(
        os: map['os'] as String? ?? 'unknown',
        version: map['version'] as String? ?? '',
        arch: map['arch'] as String? ?? '',
        isDarkMode: map['isDarkMode'] as bool? ?? false,
      );

  final String os;
  final String version;
  final String arch;
  final bool isDarkMode;

  @override
  String toString() => '$os $version ($arch)';
}

/// 当前平台没有实现时抛出——UI 可以据此隐藏功能,而不是崩。
class PlatformUnsupportedException implements Exception {
  const PlatformUnsupportedException(this.channel, this.method);

  final String channel;
  final String method;

  @override
  String toString() => '平台未实现 $channel.$method';
}

class PlatformService {
  PlatformService({
    MethodChannel? methodChannel,
    EventChannel? eventChannel,
  })  : _method = methodChannel ?? const MethodChannel(kDeviceChannel),
        _events = eventChannel ?? const EventChannel(kTicksChannel);

  final MethodChannel _method;
  final EventChannel _events;

  /// 请求-响应:`invokeMethod` 的返回值是 `dynamic`,要自己转类型。
  Future<PlatformInfo> getPlatformInfo() async {
    try {
      final Object? result = await _method.invokeMethod<Object?>('getPlatformInfo');
      if (result is! Map<Object?, Object?>) {
        throw const FormatException('原生返回的不是 Map');
      }
      return PlatformInfo.fromMap(result);
    } on MissingPluginException {
      // 当前平台(或测试环境)没有注册这个通道。
      throw const PlatformUnsupportedException(kDeviceChannel, 'getPlatformInfo');
    } on PlatformException catch (e) {
      throw PlatformUnsupportedException(kDeviceChannel, '${e.code}: ${e.message}');
    }
  }

  /// 无返回值的动作:振动/蜂鸣/系统提示音。
  Future<void> vibrate() async {
    try {
      await _method.invokeMethod<void>('vibrate');
    } on MissingPluginException {
      throw const PlatformUnsupportedException(kDeviceChannel, 'vibrate');
    } on PlatformException catch (e) {
      throw PlatformUnsupportedException(kDeviceChannel, '${e.code}: ${e.message}');
    }
  }

  /// 事件流:原生每 1 秒推一个计数。`EventChannel` 内部就是
  /// MethodChannel 上的 `listen` / `cancel` 两个调用 + 平台侧主动 send。
  Stream<int> ticks() => _events.receiveBroadcastStream().map((Object? event) {
        if (event is int) return event;
        throw FormatException('ticks 事件应为 int,实际是 ${event.runtimeType}');
      });

  /// 取消订阅时 EventChannel 会自动向原生发 `cancel`(原生据此停掉定时器)。
  void dispose() {}
}

代码构成:text 60 KB · xml 41 KB · dart 18 KB · kotlin 6 KB

本地运行

zip → 解压 → 执行
$cd examples/ch15-platform-channels && flutter run -d macos

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • flutter analyze 0 告警、flutter test 10 个用例全绿、flutter build macos --debug 真实构建
查看全部示例