【问题标题】:Future is stuck on return statement and never completes the function future called fromFuture 卡在 return 语句上,并且永远不会完成从调用的函数 future
【发布时间】:2021-12-31 20:39:20
【问题描述】:

getInitialTripData 使用 await 调用 getCurrentLocationData,但它从不打印“来这里 1”,并且在 getCurrentLocationData 上,该函数继续运行直到打印数据,然后卡在返回语句上,我不知道问题是什么

setInitialTripData() async {
    print("coming here");
    MapLocation startingPoint=await Get.find<LocationService>().getCurrentLocationData();
    print("coming here 1");
      if (startingPoint != null) {
        tripData.startingPoint = startingPoint;
        startingPointTextController.text = startingPoint.name;
        update();
      }
  }

Future<MapLocation> getCurrentLocationData()async{
   try{
     if(!locationAllowed.value){
       return null;
     }
     LocationData position=await _location.getLocation();
     List<geo.Placemark> placemark =
     await geo.placemarkFromCoordinates(position.latitude, position.longitude);
     if(placemark.length==0 || placemark==null){
       return null;
     }
     MapLocation mapLocation=MapLocation(name: "${placemark[0].name.isNotEmpty? placemark[0].name+", ":""}${placemark[0].subAdministrativeArea.isNotEmpty? placemark[0].subAdministrativeArea+", ":""}${placemark[0].isoCountryCode.isNotEmpty? placemark[0].isoCountryCode:""}",latitude: position.latitude,longitude: position.longitude);
    print(mapLocation.getDataMap());
     return mapLocation;
   }
   catch(e){
     return null;
   }
  }

【问题讨论】:

  • 开启空值安全。一点点的痛苦会带来很大的收获。你也在使用 lints 包吗?

标签: flutter dart async-await


【解决方案1】:

getCurrentLocation 有很多机会返回 null,而您没有处理 setInitialTripData 中潜在的 null 返回值

您的代码只有在 startingPoint != null 看起来如此时才会继续执行。

【讨论】:

  • 它甚至没有打印这个声明 print("coming here 1");所以它是否为空都没有关系。Future 在打印这一行后被卡住 print(mapLocation.getDataMap());只是卡在那里不返回数据
【解决方案2】:

问题出在您的 getCurrentLocationData 函数中,因为您的函数需要 MapLocation 类型的返回值,因为您已在函数中声明它是此处的返回类型

Future<MapLocation> getCurrentLocationData(){}

这就是为什么当你在这个函数中return null 这会抛出一个错误并且break 你的函数。

您需要做的是删除 return type 或将其设为 nullable,无论哪个都可以正常工作,例如:

Future<MapLocation?> getCurrentLocationData(){}

或者

Future getCurrentLocationData(){}

除此之外,您需要将receiving 变量设置为nullable 以便它可以处理null 数据

MapLocation? startingPoint=await Get.find<LocationService>().getCurrentLocationData();

【讨论】:

  • 我没有使用空安全,即使我删除类型它也不会返回它只会打印数据 print(mapLocation.getDataMap());它会停在那里
  • 尝试一次返回 Future.value() 而不是 null。
猜你喜欢
  • 2019-10-26
  • 1970-01-01
  • 2015-12-14
  • 2020-10-07
  • 2018-09-27
  • 2022-11-20
  • 2018-12-18
  • 2018-06-26
  • 2019-05-09
相关资源
最近更新 更多