-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
99 lines (88 loc) · 2.48 KB
/
main.dart
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
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_weigh_serial/flutter_weigh_serial.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late WeighSerialProvider weighSerialProvider;
StreamSubscription<WeighResult>? _subscription;
String weighData = '';
@override
void initState() {
super.initState();
weighSerialProvider = WeighSerialProvider();
}
@override
void dispose() {
_closeWeigh();
_subscription?.cancel();
super.dispose();
}
Future<void> _closeWeigh() {
return weighSerialProvider.close();
}
void _connectWeigh() {
weighSerialProvider.findAndConnect().then(
(success) {
if (success) {
Fluttertoast.showToast(msg: '称重设备连接成功');
_subscription = weighSerialProvider.weighListener?.listen(
(data) {
log('称重数据 - ${data.toMap().toString()}');
setState(() {
weighData =
'${data.weight} kg (${data.isStable ? '稳定' : '不稳定'})';
});
},
);
} else {
Fluttertoast.showToast(msg: '称重设备连接失败');
}
},
onError: (e) {
Fluttertoast.showToast(msg: '称重设备连接失败(${e.toString()})');
},
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('称重demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
weighSerialProvider.isConnect
? Text('已连接 - 称重数据: $weighData')
: const Text('未连接'),
const SizedBox(height: 15),
TextButton(
onPressed: _connectWeigh,
child: const Text('连接称重'),
),
const SizedBox(height: 15),
TextButton(
onPressed: () async {
await _closeWeigh();
setState(() {});
},
child: const Text('停止称重'),
),
],
),
),
),
);
}
}