我能够使用geolocator获取当前位置,但是我想在geolocator中不使用lastKnownLocation来缓存和恢复字符串地址。即时通讯使用共享的首选项,但不能使其正常工作。我在其他代码上多次使用了共享首选项,但是使用geolocator却很复杂。而且我对flutter / dart超级陌生
代码:
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的工作代码:
谢谢您的时间
如果我对您的理解正确,那么您要完成的操作是存储上次捕获的地址,如果没有激活GPS,则将其检索出来。为此,您可以使用SharedPreferences或SQLite,只需查看有关如何使用它们的文档即可。
找到了解决方案。只需将loadAddress()
函数替换为
void save() {
String address = _currentAddress;
saveAddress(address);
}
void _updateName(String address) {
setState(() {
this.locationCache = address;
});
}
然后将retrieveAddress().then(updateName)
放入initState()