track_page.dart 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_blue/flutter_blue.dart';
  3. import 'package:flutter_tracker/dio/login_dao.dart';
  4. import 'package:flutter_tracker/model/user_model.dart';
  5. import 'package:flutter_tracker/pages/bluetooth_off_page.dart';
  6. import 'package:flutter_tracker/utils/app_util.dart';
  7. import 'package:flutter_tracker/views/contact_card.dart';
  8. /// Description:
  9. /// Time : 2021年12月03日 Friday
  10. /// Author : liuyuqi.gov@msncn
  11. class TrackPage extends StatefulWidget {
  12. const TrackPage({Key? key}) : super(key: key);
  13. @override
  14. _TrackPageState createState() => _TrackPageState();
  15. }
  16. class _TrackPageState extends State<TrackPage> {
  17. String testText = '';
  18. List<UserModel> blueList = [];
  19. List<BluetoothDevice> devices = [];
  20. List<ScanResult> myScanResult = [];
  21. List<String> updateTime = [];
  22. FlutterBlue flutterBlue = FlutterBlue.instance;
  23. @override
  24. Widget build(BuildContext context) {
  25. return StreamBuilder<BluetoothState>(
  26. stream: FlutterBlue.instance.state,
  27. initialData: BluetoothState.unknown,
  28. builder: (c, snapshot) {
  29. final state = snapshot.data;
  30. if (state == BluetoothState.on) {
  31. return buildContent();
  32. }
  33. return BluetoothOffPage(state: state!);
  34. });
  35. }
  36. Column buildContent() {
  37. return Column(
  38. children: <Widget>[
  39. Expanded(
  40. child: Padding(
  41. padding: const EdgeInsets.only(
  42. left: 25.0,
  43. right: 25.0,
  44. bottom: 10.0,
  45. top: 30.0,
  46. ),
  47. child: Container(
  48. height: 50.0,
  49. width: double.infinity,
  50. decoration: BoxDecoration(
  51. color: Colors.deepPurple[500],
  52. borderRadius: BorderRadius.circular(20.0),
  53. boxShadow: const [
  54. BoxShadow(
  55. color: Colors.black,
  56. blurRadius: 4.0,
  57. spreadRadius: 0.0,
  58. offset: Offset(2.0, 2.0), // shadow direction: bottom right
  59. )
  60. ],
  61. ),
  62. child: Row(
  63. children: const <Widget>[
  64. Expanded(
  65. child: Image(
  66. image: AssetImage('assets/images/corona.png'),
  67. ),
  68. ),
  69. Expanded(
  70. flex: 2,
  71. child: Text(
  72. '附近用户',
  73. textAlign: TextAlign.left,
  74. style: TextStyle(
  75. fontSize: 21.0,
  76. color: Colors.white,
  77. fontWeight: FontWeight.w500,
  78. ),
  79. ),
  80. )
  81. ],
  82. ),
  83. ),
  84. ),
  85. ),
  86. buildStartButton(),
  87. Expanded(
  88. flex: 2,
  89. child: Padding(
  90. padding: const EdgeInsets.symmetric(horizontal: 25.0),
  91. child: buildListView(),
  92. ),
  93. ),
  94. ],
  95. );
  96. }
  97. Widget buildListView() {
  98. if (blueList.isNotEmpty) {
  99. return ListView.builder(
  100. itemBuilder: (context, index) {
  101. return ContactCard(
  102. imagePath: 'assets/images/green.jpg',
  103. infection: '健康',
  104. username: "李四",
  105. updateTime: updateTime[index],
  106. deviceid: blueList[index].deviceid,
  107. );
  108. },
  109. itemCount: blueList.length,
  110. );
  111. } else {
  112. return Text("");
  113. }
  114. }
  115. StreamBuilder<bool> buildStartButton() {
  116. return StreamBuilder<bool>(
  117. stream: flutterBlue.isScanning,
  118. initialData: false,
  119. builder: (context, snapshot) {
  120. if (snapshot.data!) {
  121. return Padding(
  122. padding: EdgeInsets.only(bottom: 200.0),
  123. child: ElevatedButton(
  124. style: ButtonStyle(
  125. shape: MaterialStateProperty.all(RoundedRectangleBorder(
  126. borderRadius: BorderRadius.circular(20.0))),
  127. elevation: MaterialStateProperty.all(5.0),
  128. iconColor: MaterialStateProperty.all(Colors.red),
  129. ),
  130. onPressed: () async {
  131. startTrack(snapshot.data!);
  132. },
  133. child: const Text(
  134. '停止追踪',
  135. style: TextStyle(
  136. fontSize: 20.0,
  137. fontWeight: FontWeight.bold,
  138. color: Colors.white,
  139. ),
  140. ),
  141. ),
  142. );
  143. } else {
  144. return Padding(
  145. padding: EdgeInsets.only(bottom: 200.0),
  146. child: ElevatedButton(
  147. style: ButtonStyle(
  148. shape: MaterialStateProperty.all(
  149. RoundedRectangleBorder(
  150. borderRadius: BorderRadius.circular(20.0),
  151. ),
  152. ),
  153. elevation: MaterialStateProperty.all(5.0),
  154. iconColor: MaterialStateProperty.all(Colors.deepPurple[400]),
  155. ),
  156. onPressed: () async {
  157. startTrack(snapshot.data!);
  158. },
  159. child: const Text(
  160. '开始追踪',
  161. style: TextStyle(
  162. fontSize: 20.0,
  163. fontWeight: FontWeight.bold,
  164. color: Colors.white,
  165. ),
  166. ),
  167. ),
  168. );
  169. }
  170. });
  171. }
  172. @override
  173. void initState() {
  174. super.initState();
  175. uploadMyId();
  176. // startTrack(true);
  177. }
  178. void startTrack(bool flag) async {
  179. if (flag) {
  180. flutterBlue.stopScan();
  181. } else {
  182. setState(() {
  183. blueList = [];
  184. updateTime = [];
  185. myScanResult = [];
  186. });
  187. AppUtil.buildToast("正在搜索附近的人...");
  188. flutterBlue.startScan(timeout: const Duration(seconds: 20));
  189. // 扫描周围蓝牙设备
  190. flutterBlue.scanResults.listen((scanResult) {
  191. for (ScanResult scan in scanResult) {
  192. if (!myScanResult.contains(scan)) {
  193. print("-----------------id------:" + scan.device.id.toString());
  194. setState(() {
  195. myScanResult.add(scan);
  196. blueList.add(UserModel(deviceid: scan.device.id.toString()));
  197. updateTime.add(DateTime.now().toString().substring(0, 10));
  198. });
  199. }
  200. }
  201. });
  202. // 扫描连接设备
  203. List<BluetoothDevice> connectedDevices =
  204. await flutterBlue.connectedDevices;
  205. for (BluetoothDevice device in connectedDevices) {
  206. if (!devices.contains(device)) {
  207. devices.add(device);
  208. AppUtil.buildToast("正在追踪设备\"" + device.id.toString() + "\"健康状态...");
  209. // 云端检测用户状态
  210. UserModel user =
  211. await LoginDao.getUserByDeviceId(device.id.toString());
  212. blueList.add(user);
  213. }
  214. }
  215. // String myDeviceId = await flutterBlue.localAdapter.deviceId;
  216. }
  217. // try {
  218. // bool a = await Nearby().startAdvertising(
  219. // loggedInUser.email,
  220. // strategy,
  221. // onConnectionInitiated: null,
  222. // onConnectionResult: (id, status) {
  223. // print(status);
  224. // },
  225. // onDisconnected: (id) {
  226. // print('Disconnected $id');
  227. // },
  228. // );
  229. //
  230. // print('ADVERTISING ${a.toString()}');
  231. // } catch (e) {
  232. // print(e);
  233. // }
  234. }
  235. // upload my device BluetoothCharacteristic to server
  236. void uploadMyId() async {
  237. // String myDeviceId = await flutterBlue.localAdapter.deviceId;
  238. // print("-----------------id------:" + myDeviceId);
  239. // Map<String, dynamic> params = {
  240. // "userId": loggedInUser.email,
  241. // "deviceId": myDeviceId,
  242. // };
  243. // HttpUtil.post(
  244. // '/user/updateDeviceId',
  245. // (data) {
  246. // print(data);
  247. // },
  248. // params: params,
  249. // );
  250. }
  251. }