Home > OS >  I have tried eveything in my reach but didn't get the result. All i want to get the var lat and
I have tried eveything in my reach but didn't get the result. All i want to get the var lat and

Time:06-08

import 'package:geolocator/geolocator.dart';

class Location {
  double ? lat;
  double ? lon;

  void getLocation() async {
    Position position = await _determinePosition();
    lat = position.latitude;
    lon = position.longitude;
  }

  Future < Position > _determinePosition() async {
    LocationPermission permission;
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Permission Denied');
      }
    }
    return await Geolocator.getCurrentPosition();


  }
}

As you can see the error, i can't even assign the value of lat and lon,and if i put null in there, it will show 0 in result. And i put late then,it waill show runtime error for initiatize the value before

CodePudding user response:

Important thing is : Add the permission in manifest . Use permission handler and take permission from user. After checking that we have permission, use the geolocator.

CodePudding user response:

You have to await an async method, otherwise you don't lknow whether it's done yet. Since you managed to not return a Future<>, you cannot await your method. Matter of fact you didn't even try, otherwise you would have gotten a compiler error at that point.

Future<void> getLocation() async {
  Position position = await _determinePosition();
  lat = position.latitude;
  lon = position.longitude;
}

Now you need to find where you call this method and then await it. Only then your values will be filled.

  • Related