I’m trying to fetch users coordinates with geolocator package. I’ve implemented a late initializer for coordinates type and assign value in initState. but whenever I use the late
keyword it throws an error. but I assign a string for lat and long with late
keyword, and it works fine.
late String lat;
late String long;
late Coordinates coordinates;
Future<Position> getCurrentLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error("not enabled");
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error("permission denied");
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error("ever denied");
}
return await Geolocator.getCurrentPosition();
}
@override
void initState() {
// TODO: implement initState
super.initState();
getCurrentLocation().then((value) async {
lat = "${value.latitude}";
long = "${value.longitude}";
List<Placemark> placemarks =
await placemarkFromCoordinates(value.latitude, value.longitude);
Placemark place = placemarks[0];
String currentLocation = "${place.locality}, ${place.country}";
final location = tz.getLocation(currentLocation);
DateTime date = tz.TZDateTime.from(DateTime.now(), location);
CalculationParameters params = CalculationMethod.MuslimWorldLeague();
coordinates = Coordinates(value.latitude, value.longitude);
setState(() {});
});
}
when I use lat or long in a text widget it displays the coordinates. but when I try to use coordinates.latitude
it throws Flutter LateInitializationError: Field 'fieldname' has not been initialized
error. it does the same thing when I try to assign a late initializer with such types. how can I fix this kind of problem?
3
Answers
Don’t use late and give value for all parametre
The
getCurrentLocation
is an async function, and this async function in theinit
function may set yourlat
long
variable after the engine renders the UI. In your build function, you use thelat
andlong
so it raises an error that thelat
,long
haven’t initialized yet. You should change fromlate
to var for thelat
andlong
, then the issue will be resolved.Use
FutureBuilder
and passgetCurrentLocation
method as future parameter like this: