I am trying to create a generic flutter function which presents a dialog box that automatically refreshes the current distance to a fixed position? When the dialog box is active, it will display the distance(in meters) from the current position to the fixed position(target) and automatically update as the location changes.
The code below accomplishes this for the instant the dialog box was activated, but I haven't been successful in refreshing the distance as the user moves. I have a suspicion it involves adding StatefulBuilder within the showDialog, but haven't found a solution.
Thanks in advance for any assistance.
_displayTargetDistance(BuildContext context, Position theTarget) async {
Geolocator geolocator = Geolocator();
geolocator.forceAndroidLocationManager;
Position position = await geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
double distanceInMeters = await Geolocator().distanceBetween(theTarget.latitude, theTarget.longitude, position.latitude, position.longitude);
String str = distanceInMeters.toString() + " Meters";
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Distance to Target'),
content: Text(str),
actions: <Widget>[
new FlatButton(
child: new Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}
geolocator
has a built in stream for this. I have built in my example below.Depending on your requirements, using location services can drain the users battery pretty quickly - so I have also included an intervalDuration of 5 seconds.
Also, yes you do need to add state to the dialog using
StatefulBuilder