flutterdartgeocoderflutter-getx

How do I get the address as soon as possible?


I am deveoping an app in Flutter using GetX state management, but having a difficult time getting address from GPS on the spot. I am using Geocoder and geolocator to fetch latitude, longitude, and address based on coordinates. I have a Floatingactionbutton that scans a barcode and adds some data to Firestore: latitude, longitude, and address.

The problem I am having is I am seeing data like this adding to Firestore(below). Sometimes I have to scan like 3 times before the address and coordinates are added to firestore. How do I make sure the coordinates and address are fetched first before adding to firestore. Using a stateful widget I believe I could do it in the initstate?

enter image description here

'''

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");
    }
  }
}

'''


Solution

  • It is because you are not waiting for the future to complete. You should use the await operator

      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");
        }
      }
    }