here's a screenshot of the code
the code was running well before my current position was printing on the console then I terminated the program and ran it again then it just stopped working
CodePudding user response:
Firstly, you need to decare your position variable outside the function block to be able to access it within your build Widgets.
class _LoadingScreenState extends State<LoadingScreen> {
late Position position;
// ...
Next, you need to update the position state using setState
;
// ...
setState(() {
position = await Geolocator.getCurrentPosition( /* complete the call here*/;
});
print(position);
// ...
For any more help or explanation feel free to comment below. Bye!
CodePudding user response:
The official documentation is cleared and detailed. You can consult this link geolocator, It's shows the steps to be followed during the implementation of get the current location.
- Firstly, checking is location service enabled in the device,
- Secondly, checking and requesting permission to access the position of the device.
- Finally, get location service when service is enabled and permissions are granted .
The following code, it's copied from official documentation:
import 'package:geolocator/geolocator.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}