【发布时间】:2020-05-06 13:27:08
【问题描述】:
我能够使用地理定位器获取当前位置,但我想缓存和恢复字符串地址,而不使用地理定位器中的 lastKnownLocation。我正在使用共享首选项,但无法使其正常工作。我在其他代码上多次使用共享偏好,但使用地理定位器有点复杂。我对颤振/飞镖超级新手
代码:
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
String _locationCache;
String key = "location_cache";
@override
void initState() {
super.initState();
_getCurrentLocation();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("current location = " + _currentAddress),
Text("last location = " + __locationCache) // HERE GET STORED DATA ISNT WORKING
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress = "${place.country}";
});
saveAddress();
} catch (e) {
print(e);
}
}
Future<bool> saveAddress() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(key, _currentAddress);
}
Future<String> retrieveAddress() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
return prefs.getString(key) ?? "";
}
loadAddress() {
retrieveAddress().then((value) {
setState(() {
_locationCache = value;
});
});
}
}
这里是没有 _locationCache 的工作代码:
感谢您的宝贵时间
【问题讨论】:
标签: flutter caching path geolocation sharedpreferences