123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264 |
- import 'package:flutter/material.dart';
- import 'package:flutter_blue/flutter_blue.dart';
- import 'package:flutter_tracker/dio/login_dao.dart';
- import 'package:flutter_tracker/model/user_model.dart';
- import 'package:flutter_tracker/pages/bluetooth_off_page.dart';
- import 'package:flutter_tracker/utils/app_util.dart';
- import 'package:flutter_tracker/views/contact_card.dart';
- /// Description:
- /// Time : 2021年12月03日 Friday
- /// Author : liuyuqi.gov@msncn
- class TrackPage extends StatefulWidget {
- const TrackPage({Key? key}) : super(key: key);
- @override
- State<TrackPage> createState() => _TrackPageState();
- }
- class _TrackPageState extends State<TrackPage> {
- String testText = '';
- List<UserModel> blueList = [];
- List<BluetoothDevice> devices = [];
- List<ScanResult> myScanResult = [];
- List<String> updateTime = [];
- FlutterBlue flutterBlue = FlutterBlue.instance;
- @override
- Widget build(BuildContext context) {
- return StreamBuilder<BluetoothState>(
- stream: FlutterBlue.instance.state,
- initialData: BluetoothState.unknown,
- builder: (c, snapshot) {
- final state = snapshot.data;
- if (state == BluetoothState.on) {
- return buildContent();
- }
- return BluetoothOffPage(state: state!);
- });
- }
- Column buildContent() {
- return Column(
- children: <Widget>[
- Expanded(
- child: Padding(
- padding: const EdgeInsets.only(
- left: 25.0,
- right: 25.0,
- bottom: 10.0,
- top: 30.0,
- ),
- child: Container(
- height: 50.0,
- width: double.infinity,
- decoration: BoxDecoration(
- color: Colors.deepPurple[500],
- borderRadius: BorderRadius.circular(20.0),
- boxShadow: const [
- BoxShadow(
- color: Colors.black,
- blurRadius: 4.0,
- spreadRadius: 0.0,
- offset: Offset(2.0, 2.0), // shadow direction: bottom right
- )
- ],
- ),
- child: Row(
- children: const <Widget>[
- Expanded(
- child: Image(
- image: AssetImage('assets/images/corona.png'),
- ),
- ),
- Expanded(
- flex: 2,
- child: Text(
- '附近用户',
- textAlign: TextAlign.left,
- style: TextStyle(
- fontSize: 21.0,
- color: Colors.white,
- fontWeight: FontWeight.w500,
- ),
- ),
- )
- ],
- ),
- ),
- ),
- ),
- buildStartButton(),
- Expanded(
- flex: 2,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 25.0),
- child: buildListView(),
- ),
- ),
- ],
- );
- }
- Widget buildListView() {
- if (blueList.isNotEmpty) {
- return ListView.builder(
- itemBuilder: (context, index) {
- return ContactCard(
- imagePath: 'assets/images/green.jpg',
- infection: '健康',
- username: "李四",
- updateTime: updateTime[index],
- deviceid: blueList[index].deviceid,
- );
- },
- itemCount: blueList.length,
- );
- } else {
- return const Text("");
- }
- }
- StreamBuilder<bool> buildStartButton() {
- return StreamBuilder<bool>(
- stream: flutterBlue.isScanning,
- initialData: false,
- builder: (context, snapshot) {
- if (snapshot.data!) {
- return Padding(
- padding: const EdgeInsets.only(bottom: 200.0),
- child: ElevatedButton(
- style: ButtonStyle(
- shape: MaterialStateProperty.all(RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20.0))),
- elevation: MaterialStateProperty.all(5.0),
- iconColor: MaterialStateProperty.all(Colors.red),
- ),
- onPressed: () async {
- startTrack(snapshot.data!);
- },
- child: const Text(
- '停止追踪',
- style: TextStyle(
- fontSize: 20.0,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- ),
- );
- } else {
- return Padding(
- padding: const EdgeInsets.only(bottom: 200.0),
- child: ElevatedButton(
- style: ButtonStyle(
- shape: MaterialStateProperty.all(
- RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20.0),
- ),
- ),
- elevation: MaterialStateProperty.all(5.0),
- iconColor: MaterialStateProperty.all(Colors.deepPurple[400]),
- ),
- onPressed: () async {
- startTrack(snapshot.data!);
- },
- child: const Text(
- '开始追踪',
- style: TextStyle(
- fontSize: 20.0,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- ),
- );
- }
- });
- }
- @override
- void initState() {
- super.initState();
- uploadMyId();
- // startTrack(true);
- }
- void startTrack(bool flag) async {
- if (flag) {
- flutterBlue.stopScan();
- } else {
- setState(() {
- blueList = [];
- updateTime = [];
- myScanResult = [];
- });
- AppUtil.buildToast("正在搜索附近的人...");
- flutterBlue.startScan(timeout: const Duration(seconds: 20));
- // 扫描周围蓝牙设备
- flutterBlue.scanResults.listen((scanResult) {
- for (ScanResult scan in scanResult) {
- if (!myScanResult.contains(scan)) {
- print("-----------------id------:${scan.device.id}");
- setState(() {
- myScanResult.add(scan);
- blueList.add(UserModel(deviceid: scan.device.id.toString()));
- updateTime.add(DateTime.now().toString().substring(0, 10));
- });
- }
- }
- });
- // 扫描连接设备
- List<BluetoothDevice> connectedDevices =
- await flutterBlue.connectedDevices;
- for (BluetoothDevice device in connectedDevices) {
- if (!devices.contains(device)) {
- devices.add(device);
- AppUtil.buildToast("正在追踪设备\"${device.id}\"健康状态...");
- // 云端检测用户状态
- UserModel user =
- await LoginDao.getUserByDeviceId(device.id.toString());
- blueList.add(user);
- }
- }
- // String myDeviceId = await flutterBlue.localAdapter.deviceId;
- }
- // try {
- // bool a = await Nearby().startAdvertising(
- // loggedInUser.email,
- // strategy,
- // onConnectionInitiated: null,
- // onConnectionResult: (id, status) {
- // print(status);
- // },
- // onDisconnected: (id) {
- // print('Disconnected $id');
- // },
- // );
- //
- // print('ADVERTISING ${a.toString()}');
- // } catch (e) {
- // print(e);
- // }
- }
- // upload my device BluetoothCharacteristic to server
- void uploadMyId() async {
- // String myDeviceId = await flutterBlue.localAdapter.deviceId;
- // print("-----------------id------:" + myDeviceId);
- // Map<String, dynamic> params = {
- // "userId": loggedInUser.email,
- // "deviceId": myDeviceId,
- // };
- // HttpUtil.post(
- // '/user/updateDeviceId',
- // (data) {
- // print(data);
- // },
- // params: params,
- // );
- }
- }
|