跳到正文
教程首页
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/main.dart
// 第 15 章 · 平台通道:MethodChannel(请求-响应)+ EventChannel(事件流)。
//
// 原生实现位置:
//   macOS  macos/Runner/MainFlutterWindow.swift
//   Android android/app/src/main/kotlin/.../MainActivity.kt
//   iOS    ios/Runner/AppDelegate.swift
//
// 通道名三处必须一致:ch15.platform/device 与 ch15.platform/ticks。
import 'package:flutter/material.dart';

import 'src/platform_service.dart';

void main() {
  runApp(const PlatformChannelApp());
}

class PlatformChannelApp extends StatelessWidget {
  const PlatformChannelApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '平台通道',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4527A0)),
      ),
      home: const PlatformPage(),
    );
  }
}

class PlatformPage extends StatefulWidget {
  const PlatformPage({super.key});

  @override
  State<PlatformPage> createState() => _PlatformPageState();
}

class _PlatformPageState extends State<PlatformPage> {
  final PlatformService _service = PlatformService();

  PlatformInfo? _info;
  String? _error;
  String _status = '尚未调用';

  /// 流只创建一次:每次 build 都新建 Stream 会让 EventChannel 反复 listen/cancel。
  late final Stream<int> _tickStream = _service.ticks();

  @override
  void initState() {
    super.initState();
    _loadInfo();
  }

  Future<void> _loadInfo() async {
    try {
      final PlatformInfo info = await _service.getPlatformInfo();
      if (!mounted) return;
      setState(() {
        _info = info;
        _error = null;
        _status = 'getPlatformInfo 成功';
      });
      // 便于真实运行验证:日志里能直接看到原生返回的内容
      debugPrint('platform info: ${info.os} ${info.version} (${info.arch})');
    } on PlatformUnsupportedException catch (e) {
      if (!mounted) return;
      setState(() {
        _error = '$e';
        _status = '原生未实现';
      });
    } on Object catch (e) {
      // 兜底:通道层的任何意外都不该让页面白屏
      if (!mounted) return;
      setState(() {
        _error = '$e';
        _status = '调用失败';
      });
    }
  }

  Future<void> _vibrate() async {
    try {
      await _service.vibrate();
      if (!mounted) return;
      setState(() => _status = 'vibrate 已调用');
    } on PlatformUnsupportedException catch (e) {
      if (!mounted) return;
      setState(() => _status = '$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(title: const Text('平台通道')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Card(
            margin: EdgeInsets.zero,
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('MethodChannel:getPlatformInfo', style: theme.textTheme.titleMedium),
                  const SizedBox(height: 8),
                  if (_error != null)
                    Text('未实现:$_error', key: const Key('info-error'))
                  else if (_info == null)
                    const Text('读取中…', key: Key('info-loading'))
                  else ...[
                    Text('OS: ${_info!.os}', key: const Key('info-os')),
                    Text('版本: ${_info!.version}', key: const Key('info-version')),
                    Text('架构: ${_info!.arch}', key: const Key('info-arch')),
                    Text('系统深色模式: ${_info!.isDarkMode ? '是' : '否'}',
                        key: const Key('info-dark')),
                  ],
                  const SizedBox(height: 8),
                  Wrap(
                    spacing: 8,
                    children: [
                      OutlinedButton(
                        key: const Key('reload-info'),
                        onPressed: _loadInfo,
                        child: const Text('重新读取'),
                      ),
                      FilledButton(
                        key: const Key('vibrate'),
                        onPressed: _vibrate,
                        child: const Text('振动 / 蜂鸣'),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text('状态: $_status', key: const Key('status')),
                ],
              ),
            ),
          ),
          const SizedBox(height: 12),
          Card(
            margin: EdgeInsets.zero,
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('EventChannel:原生每秒推一个计数', style: theme.textTheme.titleMedium),
                  const SizedBox(height: 8),
                  StreamBuilder<int>(
                    key: const Key('ticks-stream'),
                    stream: _tickStream,
                    builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                      if (snapshot.hasError) {
                        return Text('事件流错误: ${snapshot.error}', key: const Key('ticks-error'));
                      }
                      final int value = snapshot.data ?? 0;
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('收到 $value 次事件', key: const Key('ticks-count')),
                          const SizedBox(height: 4),
                          LinearProgressIndicator(value: (value % 5) / 5),
                        ],
                      );
                    },
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '离开本页时 EventChannel 会自动发 cancel,原生据此停掉定时器。',
                    style: theme.textTheme.bodySmall,
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 12),
          Card(
            margin: EdgeInsets.zero,
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('实现位置', style: theme.textTheme.titleMedium),
                  const SizedBox(height: 6),
                  const Text('macOS:  macos/Runner/MainFlutterWindow.swift'),
                  const Text('Android: android/app/src/main/kotlin/.../MainActivity.kt'),
                  const Text('iOS:    ios/Runner/AppDelegate.swift'),
                  const SizedBox(height: 6),
                  Text(
                    '本机验证的是 macOS 实现;Android/iOS 代码同构,未在真机验证。',
                    style: theme.textTheme.bodySmall,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

代码构成: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 真实构建
查看全部示例