我用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
?
你可以在provider文件
中提供一个方法class LocationProvider with ChangeNotifier {
LatLng? _location;
LatLng? get location => _location;
Future<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
,如:
Future<void>? _myFuture;
final _provider = Provider.of<LocationProvider>(listen: false);
_myFuture = _provider.initializeLocation();
,然后在FutureBuilder
中,在future
_myFuture
PS:?
可以被排除,如果你不在null safe
模式下使用dart
根据您的代码,
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 } );