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.dart209 行 · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// 第 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 真实构建