track_page.dart 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/utils/app_util.dart';
  6. import 'package:flutter_tracker/views/contact_card.dart';
  7. import 'bluetooth_off_page.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: RaisedButton(
  124. shape: RoundedRectangleBorder(
  125. borderRadius: BorderRadius.circular(20.0)),
  126. elevation: 5.0,
  127. color: Colors.red,
  128. onPressed: () async {
  129. startTrack(snapshot.data);
  130. },
  131. child: const Text(
  132. '停止追踪',
  133. style: TextStyle(
  134. fontSize: 20.0,
  135. fontWeight: FontWeight.bold,
  136. color: Colors.white,
  137. ),
  138. ),
  139. ),
  140. );
  141. } else {
  142. return Padding(
  143. padding: EdgeInsets.only(bottom: 200.0),
  144. child: RaisedButton(
  145. shape: RoundedRectangleBorder(
  146. borderRadius: BorderRadius.circular(20.0)),
  147. elevation: 5.0,
  148. color: Colors.deepPurple[400],
  149. onPressed: () async {
  150. startTrack(snapshot.data);
  151. },
  152. child: const Text(
  153. '开始追踪',
  154. style: TextStyle(
  155. fontSize: 20.0,
  156. fontWeight: FontWeight.bold,
  157. color: Colors.white,
  158. ),
  159. ),
  160. ),
  161. );
  162. }
  163. });
  164. }
  165. @override
  166. void initState() {
  167. super.initState();
  168. uploadMyId();
  169. // startTrack(true);
  170. }
  171. void startTrack(bool flag) async {
  172. if (flag) {
  173. flutterBlue.stopScan();
  174. } else {
  175. setState(() {
  176. blueList = [];
  177. updateTime = [];
  178. myScanResult = [];
  179. });
  180. AppUtil.buildToast("正在搜索附近的人...");
  181. flutterBlue.startScan(timeout: const Duration(seconds: 20));
  182. // 扫描周围蓝牙设备
  183. flutterBlue.scanResults.listen((scanResult) {
  184. for (ScanResult scan in scanResult) {
  185. if (!myScanResult.contains(scan)) {
  186. print("-----------------id------:" + scan.device.id.toString());
  187. setState(() {
  188. myScanResult.add(scan);
  189. blueList.add(UserModel(deviceid: scan.device.id.toString()));
  190. updateTime.add(DateTime.now().toString().substring(0, 10));
  191. });
  192. }
  193. }
  194. });
  195. // 扫描连接设备
  196. List<BluetoothDevice> connectedDevices =
  197. await flutterBlue.connectedDevices;
  198. for (BluetoothDevice device in connectedDevices) {
  199. if (!devices.contains(device)) {
  200. devices.add(device);
  201. AppUtil.buildToast("正在追踪设备\"" + device.id.toString() + "\"健康状态...");
  202. // 云端检测用户状态
  203. UserModel user =
  204. await LoginDao.getUserByDeviceId(device.id.toString());
  205. blueList.add(user);
  206. }
  207. }
  208. // String myDeviceId = await flutterBlue.localAdapter.deviceId;
  209. }
  210. // try {
  211. // bool a = await Nearby().startAdvertising(
  212. // loggedInUser.email,
  213. // strategy,
  214. // onConnectionInitiated: null,
  215. // onConnectionResult: (id, status) {
  216. // print(status);
  217. // },
  218. // onDisconnected: (id) {
  219. // print('Disconnected $id');
  220. // },
  221. // );
  222. //
  223. // print('ADVERTISING ${a.toString()}');
  224. // } catch (e) {
  225. // print(e);
  226. // }
  227. }
  228. // upload my device BluetoothCharacteristic to server
  229. void uploadMyId() async {
  230. // String myDeviceId = await flutterBlue.localAdapter.deviceId;
  231. // print("-----------------id------:" + myDeviceId);
  232. // Map<String, dynamic> params = {
  233. // "userId": loggedInUser.email,
  234. // "deviceId": myDeviceId,
  235. // };
  236. // HttpUtil.post(
  237. // '/user/updateDeviceId',
  238. // (data) {
  239. // print(data);
  240. // },
  241. // params: params,
  242. // );
  243. }
  244. }