示例工程 ch15-platform-channels
ch15-platform-channels/lib/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,
),
],
),
),
),
],
),
);
}
}