I'm awaiting a GEOLOCATOR function to fetch location from the user. But during the initial build I always get an error(latitude was called on null) for a few seconds before the location is actually retrieved from the GEOLOCATOR. How do I make it so that the LOCATION is actually fetched before the page is built?
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class DistancingPage extends StatefulWidget {
DistancingPage(this.uid);
@override
_DistancingPageState createState() => _DistancingPageState();
}
class _DistancingPageState extends State<DistancingPage> {
Position position;
@override
void initState() {
super.initState();
getPos();
}
Future<void> getPos() async {
Position p = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
setState(() {
position = p;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Distancing Alerts'),
backgroundColor: Colors.red[800],
),
body: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
children: [
Text(
'YOUR CURRENT POSITION',
style: TextStyle(
color: Colors.red[800],
),
), //THE ERROR OCCURS HERE
Text(position.latitude.toString() +
'° N , ' +
position.longitude.toString() +
'° E'),
],
)));
}
}