Как получить адрес как можно быстрее?

Я разрабатываю приложение во Flutter, используя управление состоянием GetX, но мне трудно получить адрес от GPS на месте. Я использую геокодер и геолокатор для получения широты, долготы и адреса на основе координат. У меня есть кнопка Floatingaction, которая сканирует штрих-код и добавляет некоторые данные в Firestore: широту, долготу и адрес.

Проблема, с которой я сталкиваюсь, заключается в том, что я вижу такие данные, добавляемые в Firestore (ниже). Иногда мне приходится сканировать примерно 3 раза, прежде чем адрес и координаты будут добавлены в firestore. Как мне убедиться, что координаты и адрес извлекаются первыми перед добавлением в firestore. Я думаю, что с помощью виджета с отслеживанием состояния я мог бы сделать это в состоянии инициализации?

введите здесь описание изображения

'''

class ScanController extends GetxController {
  final userName = "".obs;
  String name = "";
  String latitude, longitude;
  String address = "";
  String timeFormat = "";
  String result = "Hey there !";
  List scannedLocation = [];
  Future<String> futureAddress;

  Future<String> getUserDisplayName() async {
    final snapshot =
        await _firestore.collection('users').doc(_auth.currentUser.uid).get();
    name = snapshot.data()['displayName'];
    return name;
  }

  setName() async {
    String returnString = await getUserDisplayName();
    userName(returnString);
    update();
  }

  setSnackBar(title, message) {
    Get.snackbar(title, message,
        duration: Duration(seconds: 3),
        backgroundColor: Colors.black,
        colorText: Colors.white,
        snackPosition: SnackPosition.BOTTOM);
    update();
  }

  getCurrentLocation() async {
    try {
      final position = await Geolocator()
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

      latitude = '${position.latitude}';
      longitude = '${position.longitude}';
    } catch (e) {
      setSnackBar("Hello", "getCurrentLocation() Error: $e");
    }
  }

  Future<String> getAddressBasedOnLocation() async {
    try {
      final coordinates =
          new Coordinates(double.parse(latitude), double.parse(longitude));

      var addresses =
          await Geocoder.local.findAddressesFromCoordinates(coordinates);

      address = addresses.first.addressLine;
    } catch (e) {
      setSnackBar("Hello", "getAddressBasedOnLocation Error: $e");
    }
    return address;
  }

  Future scanQR() async {
    try {
      // QR data
      String qrResult = await BarcodeScanner.scan();

      // String location to be outputted onto screen
      String locationOneTime;

      // Current date and time
      final now = DateTime.now();
      timeFormat = DateFormat('hh:mm a').format(now);

      // get latitude and longitude coordinates
      getCurrentLocation();

      // get address based on latitude and longitude
      futureAddress = getAddressBasedOnLocation();
      address.toString();

      locationOneTime = '$qrResult scanned at $timeFormat in $address';
      print(locationOneTime);
      scannedLocation.add(locationOneTime);

      setSnackBar("Notification", "Scan Successful");

      result = qrResult;
      _firestore.collection('messages').add({
        'user': _auth.currentUser.email,
        'location': result,
        'timestamp': FieldValue.serverTimestamp(),
        'coordinates': '$latitude: $longitude',
        'address': '$address',
      });
    } on PlatformException catch (ex) {
      if (ex.code == BarcodeScanner.CameraAccessDenied) {
        setSnackBar("Hello", "Camera permission was denied");
      } else {
        setSnackBar("Hello", "Unknown error $ex");
      }
    } on FormatException {
      setSnackBar(
          "Hello", "You pressed the back button before scanning anything");
    } catch (ex) {
      setSnackBar("Hello", "Unknown Error $ex");
    }
  }
}

'''


person user2827326    schedule 15.04.2021    source источник


Ответы (1)


Это потому, что вы не ждете завершения будущего. Вы должны использовать оператор await

  Future scanQR() async {
    try {
      // QR data
      String qrResult = await BarcodeScanner.scan();

      // String location to be outputted onto screen
      String locationOneTime;

      // Current date and time
      final now = DateTime.now();
      timeFormat = DateFormat('hh:mm a').format(now);

      // get latitude and longitude coordinates
      // add await here
      await getCurrentLocation();

      // get address based on latitude and longitude
                     //// add await here
      futureAddress = await getAddressBasedOnLocation();
      address.toString();

      locationOneTime = '$qrResult scanned at $timeFormat in $address';
      print(locationOneTime);
      scannedLocation.add(locationOneTime);

      setSnackBar("Notification", "Scan Successful");

      result = qrResult;
      _firestore.collection('messages').add({
        'user': _auth.currentUser.email,
        'location': result,
        'timestamp': FieldValue.serverTimestamp(),
        'coordinates': '$latitude: $longitude',
        'address': '$address',
      });
    } on PlatformException catch (ex) {
      if (ex.code == BarcodeScanner.CameraAccessDenied) {
        setSnackBar("Hello", "Camera permission was denied");
      } else {
        setSnackBar("Hello", "Unknown error $ex");
      }
    } on FormatException {
      setSnackBar(
          "Hello", "You pressed the back button before scanning anything");
    } catch (ex) {
      setSnackBar("Hello", "Unknown Error $ex");
    }
  }
}
person thenoobslayer    schedule 15.04.2021
comment
Большое спасибо!! Это сработало! - person user2827326; 16.04.2021
comment
Попробуйте отметить это как правильный ответ - person thenoobslayer; 16.04.2021