谷歌附近的 Flutter 蓝牙

问题描述

我对 Covid 项目有问题,它依赖于带有蓝牙的 Nearby Google 服务。 我的问题是:我找不到附近的设备:-

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:Flutter/material.dart';
import 'package:location/location.dart';
import 'package:nearby_connections/nearby_connections.dart';

import 'components/contact_card.dart';
import 'constants.dart';

class NearbyInterface extends StatefulWidget {
  static const String id = 'nearby_interface';

  @override
  _NearbyInterfaceState createState() => _NearbyInterfaceState();
}

class _NearbyInterfaceState extends State<NearbyInterface> {
  Location location = Location();
  Firestore _firestore = Firestore.instance;
  final Strategy strategy = Strategy.P2P_STAR;
  FirebaseUser loggedInUser;
  String testText = '';
  final _auth = FirebaseAuth.instance;
  List<dynamic> contactTraces = [];
  List<dynamic> contactTimes = [];
  List<dynamic> contactLocations = [];

  void addContactsToList() async {
    await getCurrentUser();

    _firestore
        .collection('users')
        .document(loggedInUser.email)
        .collection('met_with')
        .snapshots()
        .listen((snapshot) {
      for (var doc in snapshot.documents) {
        String currUsername = doc.data['username'];
        DateTime currTime = doc.data.containsKey('contact time')
            ? (doc.data['contact time'] as Timestamp).toDate()
            : null;
        String currLocation = doc.data.containsKey('contact location')
            ? doc.data['contact location']
            : null;

        if (!contactTraces.contains(currUsername)) {
          contactTraces.add(currUsername);
          contactTimes.add(currTime);
          contactLocations.add(currLocation);
        }
      }
      setState(() {});
      print(loggedInUser.email);
    });
  }

  void deleteOldContacts(int threshold) async {
    await getCurrentUser();
    DateTime timeNow = DateTime.Now(); //get today's time

    _firestore
        .collection('users')
        .document(loggedInUser.email)
        .collection('met_with')
        .snapshots()
        .listen((snapshot) {
      for (var doc in snapshot.documents) {
//        print(doc.data.containsKey('contact time'));
        if (doc.data.containsKey('contact time')) {
          DateTime contactTime = (doc.data['contact time'] as Timestamp)
              .toDate(); // get last contact time
          // if time since contact is greater than threshold than remove the contact
          if (timeNow.difference(contactTime).inDays > threshold) {
            doc.reference.delete();
          }
        }
      }
    });

    setState(() {});
  }

  void discovery() async {
    try {
      print("---------------------------");
      print((await location.getLocation()).toString());
      print(DateTime.Now().toString());
      bool a = await Nearby().startdiscovery(
        loggedInUser.email,strategy,onEndpointFound: (id,name,serviceId) async {
          print('I saw id:$id with name:$name'); // the name here is an email

          var docRef =
              _firestore.collection('users').document(loggedInUser.email);

          //  When I discover someone I will see their email and add that email to the database of my contacts
          //  also get the current time & location and add it to the database
          docRef.collection('met_with').document(name).setData({
            'username': await getUsernameOfEmail(email: name),'contact time': DateTime.Now(),'contact location': (await location.getLocation()).toString(),});
        },onEndpointLost: (id) {
          print(id);
        },serviceId: "com.egypt.covid",);
      print('disCOVERING: ${a.toString()}');
    } catch (e) {
      print(e);
    }
  }

  void getPermissions() {
    Nearby().askLocationAndExternalStoragePermission();
  }

  Future<String> getUsernameOfEmail({String email}) async {
    String res = '';
    await _firestore.collection('users').document(email).get().then((doc) {
      if (doc.exists) {
        res = doc.data['username'];
      } else {
        // doc.data() will be undefined in this case
        print("No such document!");
      }
    });
    return res;
  }

  Future<void> getCurrentUser() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
    deleteOldContacts(14);
    addContactsToList();
    getPermissions();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Icon(
          Icons.menu,color: Colors.deepPurple[800],),centerTitle: true,title: Text(
          'TracerX',style: TextStyle(
            color: Colors.deepPurple[800],fontWeight: FontWeight.bold,fontSize: 28.0,backgroundColor: Colors.white,body: Column(
        children: <Widget>[
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(
                left: 25.0,right: 25.0,bottom: 10.0,top: 30.0,child: Container(
                height: 100.0,width: double.infinity,decoration: Boxdecoration(
                  color: Colors.deepPurple[500],borderRadius: BorderRadius.circular(20.0),BoxShadow: [
                    BoxShadow(
                      color: Colors.black,blurRadius: 4.0,spreadRadius: 0.0,offset:
                          Offset(2.0,2.0),// shadow direction: bottom right
                    )
                  ],child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Image(
                        image: Assetimage('images/corona.png'),Expanded(
                      flex: 2,child: Text(
                        'Your Contact Traces',textAlign: TextAlign.left,style: TextStyle(
                          fontSize: 21.0,color: Colors.white,fontWeight: FontWeight.w500,)
                  ],Padding(
            padding: EdgeInsets.only(bottom: 30.0),child: RaisedButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.0)),elevation: 5.0,color: Colors.deepPurple[400],onpressed: () async {
                try {
                  bool a = await Nearby().startAdvertising(
                    loggedInUser.email,onConnectionInitiated: null,onConnectionResult: (id,status) {
                      print(status);
                    },ondisconnected: (id) {
                      print('disconnected $id');
                    },);

                  print('ADVERTISING ${a.toString()}');
                } catch (e) {
                  print(e);
                }

                discovery();
              },child: Text(
                'Start Tracing',style: kButtonTextStyle,Expanded(
            flex: 2,child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 25.0),child: ListView.builder(
                itemBuilder: (context,index) {
                  return ContactCard(
                    imagePath: 'images/profile1.jpg',email: contactTraces[index],infection: 'Not-Infected',contactUsername: contactTraces[index],contactTime: contactTimes[index],contactLocation: contactLocations[index],);
                },itemCount: contactTraces.length,],);
  }
}

这是注册文件:-

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:contacttracingprototype/components/rounded_button.dart';
import 'package:contacttracingprototype/constants.dart';
import 'package:contacttracingprototype/nearby_interface.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:Flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class RegistrationScreen extends StatefulWidget {
  static const String id = 'registration_screen';
  @override
  _RegistrationScreenState createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  final _auth = FirebaseAuth.instance;
  Firestore _firestore = Firestore.instance;
  bool showSpinner = false;
  String email;
  String password;
  String userName;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,body: Container(
        decoration: Boxdecoration(
          image: decorationImage(
            image: Assetimage('images/bg1.jpg'),fit: BoxFit.cover,child: ModalProgressHUD(
          inAsyncCall: showSpinner,child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.0),child: Column(
              mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.stretch,children: <Widget>[
                TextField(
                  textAlign: TextAlign.center,onChanged: (value) {
                    userName = value;
                  },decoration:
                      kTextFielddecoration.copyWith(hintText: 'Username'),SizedBox(
                  height: 8.0,TextField(
                  keyboardType: TextInputType.emailAddress,textAlign: TextAlign.center,onChanged: (value) {
                    email = value;
                  },decoration: kTextFielddecoration.copyWith(
                      hintText: 'Enter your email'),TextField(
                  obscureText: true,onChanged: (value) {
                    password = value;
                  },decoration: kTextFielddecoration.copyWith(
                      hintText: 'Enter your password'),SizedBox(
                  height: 24.0,RoundedButton(
                  title: 'Register',colour: Colors.deepPurpleAccent,onpressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      final newUser =
                          await _auth.createuserWithEmailAndPassword(
                              email: email,password: password);
                      if (newUser != null) {
                        _firestore.collection('users').document(email).setData({
                          'username': userName,});
                        Navigator.pushNamed(context,NearbyInterface.id);
                      }
                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      print(e);
                    }
                  },);
  }
}

上面的代码来发现附近的蓝牙设备并将他添加到他的列表中..所以我的问题是: 为什么我在附近找不到这些设备。 上面的代码发现附近的蓝牙设备并将他添加到他的列表中..所以我的问题是: 为什么我在附近找不到这些设备。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)