将 Future<var> 分配给 var

Assign Future<var> to var

我有一些用 dart 编写的代码,我在其中使用 provider 包来更新地图上图钉的位置。我想要它做的是让初始位置等于用户的当前位置,然后如果他们拖动图钉,它将更新到图钉被放下的任何地方。

我的问题是初始位置变量需要 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

根据您的代码,

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 } ); 

您可以在提供程序文件中简单地使用一个方法

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 模式下使用飞镖 ? 可以排除