我有一些用 dart 撰寫的代碼,我使用提供程式包來更新地圖上圖釘的位置。我想要它做的是讓初始位置等于用戶的當前位置,然后如果他們拖動圖釘,它將更新到圖釘掉落的任何地方。
我的問題是初始位置變數需要Future<LatLng>,但是,當我更新位置時它最終只是LatLng并且我不能將它分配給_location變數。
class LocationProvider with ChangeNotifier {
Future<LatLng> _location = LocationService().getLocation();
// Error here, wants it to be Future<LatLng>
LatLng get location => _location;
void calculateNewLocation(oldLocation, zoom, offset) {
var newPoint = const Epsg3857().latLngToPoint(oldLocation, zoom)
CustomPoint(offset.dx, offset.dy);
LatLng? newLocation = const Epsg3857().pointToLatLng(newPoint, zoom);
// Error here again for the same reason
_location = newLocation ?? _location;
notifyListeners();
}
}
我如何做到這一點,以便我可以將這兩個值都分配給_location?
uj5u.com熱心網友回復:
您可以簡單地在提供程式檔案中有一個方法
class LocationProvider with ChangeNotifier {
LatLng? _location;
LatLng? get location => _location;
void initializeLocation() async {
_location = await LocationService().getLocation();
notifyListeners();
}
void calculateNewLocation(oldLocation, zoom, offset) {
var newPoint = const Epsg3857().latLngToPoint(oldLocation, zoom)
CustomPoint(offset.dx, offset.dy);
LatLng? newLocation = const Epsg3857().pointToLatLng(newPoint, zoom);
_location = newLocation ?? _location;
notifyListeners();
}
}
initializeLocation然后,當您希望它被初始化時,您必須呼叫它,例如:
final _provider = Provider.of<LocationProvider>(listen: false);
_provider.initializeLocation();
PS:?如果您不在null safe模式下使用飛鏢,可以排除
uj5u.com熱心網友回復:
根據您的代碼,
LocationService().getLocation() returns a future, so you have to either await/async or use then().
試試這些
Future<LatLng> _location = LocationService().getLocation();
LatLng get location = await _location; // put this in a separate method with async keyword
或者
LocationService().getLocation().then((value) { location = value } );
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480543.html
