'Future<GeoFirePoint>' 不是类型转换中类型 'GeoFirePoint' 的子类型

'Future<GeoFirePoint>' is not a subtype of type 'GeoFirePoint' in type cast

我有一个获取坐标纬度和经度的函数:

Future <GeoFirePoint> getCenter() async  {

var center = await geolocatorService.getInitialLocation()

       .then  (  (position)  {

          return GeoFirePoint( position.latitude, position.longitude);

   }, onError: throw Exception('Intentional exception')
       );}

当我尝试分配它时:

late GeoFirePoint center =  getCenter() as GeoFirePoint;

我收到上述错误。尝试使用 async /waits 来填充该函数,但我似乎遗漏了一些东西。如果我删除演员表,会出现更多问题。

问题是,您的 getCenter() 函数 returns 是 GeoFirePointFuture

late GeoFirePoint center;

Future <GeoFirePoint> getCenter() async  {
 final position = await geolocatorService.getInitialLocation();
 center = GeoFirePoint(position.latitude, position.longitude);
}

这会为您的变量分配正确的值。要捕获异常,您可以将包含 await 关键字的行包装在 try/catch 块中。

不是将 getCenter() 值分配给变量 center,而是使用 FutureBuildergetCenter() 中获取值,就像这样

FutureBuilder<GeoFirePoint>(
      future: getCenter(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Text('Loading...');
        }
        return Text('${snapshot.data}'); /// snapshot.data is the type of GeoFirePoint
      },
    );