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
library;
import 'package:flutter/services.dart';
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)';
}
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;
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}');
}
}
Stream<int> ticks() => _events.receiveBroadcastStream().map((Object? event) {
if (event is int) return event;
throw FormatException('ticks 事件应为 int,实际是 ${event.runtimeType}');
});
void dispose() {}
}