track_page.dart 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_blue/flutter_blue.dart';
  3. import 'package:flutter_tracker/dio/track_dao.dart';
  4. import 'package:flutter_tracker/model/user_model.dart';
  5. import 'package:flutter_tracker/views/contact_card.dart';
  6. import 'package:nearby_connections/nearby_connections.dart';
  7. import 'package:shared_preferences/shared_preferences.dart';
  8. import 'bluetooth_off_page.dart';
  9. /// Description:
  10. /// Time : 2021年12月03日 Friday
  11. /// Author : liuyuqi.gov@msncn
  12. class TrackPage extends StatefulWidget {
  13. const TrackPage({Key key}) : super(key: key);
  14. @override
  15. _TrackPageState createState() => _TrackPageState();
  16. }
  17. class _TrackPageState extends State<TrackPage> {
  18. String testText = '';
  19. final Strategy strategy = Strategy.P2P_STAR;
  20. UserModel currentUser;
  21. List<UserModel> blueList = [];
  22. List<BluetoothDevice> devices = [];
  23. List<ScanResult> myScanResult = [];
  24. List<String> updateTime = [];
  25. List<UserModel> users = [];
  26. FlutterBlue flutterBlue = FlutterBlue.instance;
  27. @override
  28. Widget build(BuildContext context) {
  29. return StreamBuilder<BluetoothState>(
  30. stream: FlutterBlue.instance.state,
  31. initialData: BluetoothState.unknown,
  32. builder: (c, snapshot) {
  33. final state = snapshot.data;
  34. if (state == BluetoothState.on) {
  35. return buildContent();
  36. }
  37. return BluetoothOffPage(state: state);
  38. });
  39. }
  40. Column buildContent() {
  41. return Column(
  42. children: <Widget>[
  43. Expanded(
  44. child: Padding(
  45. padding: const EdgeInsets.only(
  46. left: 25.0,
  47. right: 25.0,
  48. bottom: 10.0,
  49. top: 30.0,
  50. ),
  51. child: Container(
  52. height: 50.0,
  53. width: double.infinity,
  54. decoration: BoxDecoration(
  55. color: Colors.deepPurple[500],
  56. borderRadius: BorderRadius.circular(20.0),
  57. boxShadow: const [
  58. BoxShadow(
  59. color: Colors.black,
  60. blurRadius: 4.0,
  61. spreadRadius: 0.0,
  62. offset: Offset(2.0, 2.0), // shadow direction: bottom right
  63. )
  64. ],
  65. ),
  66. child: Row(
  67. children: const <Widget>[
  68. Expanded(
  69. child: Image(
  70. image: AssetImage('assets/images/corona.png'),
  71. ),
  72. ),
  73. Expanded(
  74. flex: 2,
  75. child: Text(
  76. '附近用户',
  77. textAlign: TextAlign.left,
  78. style: TextStyle(
  79. fontSize: 21.0,
  80. color: Colors.white,
  81. fontWeight: FontWeight.w500,
  82. ),
  83. ),
  84. )
  85. ],
  86. ),
  87. ),
  88. ),
  89. ),
  90. buildStartButton(),
  91. Expanded(
  92. flex: 2,
  93. child: Padding(
  94. padding: const EdgeInsets.symmetric(horizontal: 25.0),
  95. child: buildListView(),
  96. ),
  97. ),
  98. ],
  99. );
  100. }
  101. Widget buildListView() {
  102. if (blueList.isNotEmpty) {
  103. return ListView.builder(
  104. itemBuilder: (context, index) {
  105. return ContactCard(
  106. imagePath: 'assets/images/green.jpg',
  107. infection: '健康',
  108. username: "李四",
  109. updateTime: updateTime[index],
  110. deviceid: blueList[index].deviceid,
  111. );
  112. },
  113. itemCount: blueList.length,
  114. );
  115. } else {
  116. return Text("");
  117. }
  118. }
  119. StreamBuilder<bool> buildStartButton() {
  120. return StreamBuilder<bool>(
  121. stream: flutterBlue.isScanning,
  122. initialData: false,
  123. builder: (context, snapshot) {
  124. if (snapshot.data) {
  125. return Padding(
  126. padding: EdgeInsets.only(bottom: 200.0),
  127. child: RaisedButton(
  128. shape: RoundedRectangleBorder(
  129. borderRadius: BorderRadius.circular(20.0)),
  130. elevation: 5.0,
  131. color: Colors.red,
  132. onPressed: () async {
  133. startTrack(snapshot.data);
  134. },
  135. child: const Text(
  136. '停止追踪',
  137. style: TextStyle(
  138. fontSize: 20.0,
  139. fontWeight: FontWeight.bold,
  140. color: Colors.white,
  141. ),
  142. ),
  143. ),
  144. );
  145. } else {
  146. return Padding(
  147. padding: EdgeInsets.only(bottom: 200.0),
  148. child: RaisedButton(
  149. shape: RoundedRectangleBorder(
  150. borderRadius: BorderRadius.circular(20.0)),
  151. elevation: 5.0,
  152. color: Colors.deepPurple[400],
  153. onPressed: () async {
  154. startTrack(snapshot.data);
  155. },
  156. child: const Text(
  157. '开始追踪',
  158. style: TextStyle(
  159. fontSize: 20.0,
  160. fontWeight: FontWeight.bold,
  161. color: Colors.white,
  162. ),
  163. ),
  164. ),
  165. );
  166. }
  167. });
  168. }
  169. @override
  170. void initState() {
  171. super.initState();
  172. addContactsToList();
  173. getPermissions();
  174. }
  175. void discovery() async {
  176. try {
  177. bool a = await Nearby().startDiscovery(currentUser.username, strategy,
  178. onEndpointFound: (id, name, serviceId) async {
  179. // 保存数据
  180. }, onEndpointLost: (id) {
  181. print(id);
  182. });
  183. print('DISCOVERING: ${a.toString()}');
  184. } catch (e) {
  185. print(e);
  186. }
  187. }
  188. void getPermissions() async {
  189. Nearby().askLocationAndExternalStoragePermission();
  190. }
  191. Future<void> getCurrentUser() async {
  192. SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  193. UserModel user = sharedPreferences.get("user");
  194. }
  195. void addContactsToList() async {
  196. await getCurrentUser();
  197. // 服务器获取当前用户数据
  198. SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  199. String token = sharedPreferences.getString("token");
  200. setState(() async {
  201. users = await TrackDao.getContactList(token);
  202. });
  203. }
  204. void startTrack(bool flag) async {
  205. try {
  206. bool a = await Nearby().startAdvertising(
  207. currentUser.username,
  208. strategy,
  209. onConnectionInitiated: null,
  210. onConnectionResult: (id, status) {
  211. print(status);
  212. },
  213. onDisconnected: (id) {
  214. print('Disconnected $id');
  215. },
  216. );
  217. // 上传追踪数据
  218. SharedPreferences sharedPreferences =
  219. await SharedPreferences.getInstance();
  220. String token = sharedPreferences.getString("token");
  221. TrackDao.uploadContact(token);
  222. print('ADVERTISING ${a.toString()}');
  223. } catch (e) {
  224. print(e);
  225. }
  226. discovery();
  227. }
  228. }