gpt4 book ai didi

flutter - Dart:即使在调用异步Setter之后,Getter也会返回null(确保该方法中的字段不为null)

转载 作者:行者123 更新时间:2023-12-03 04:25:54 25 4
gpt4 key购买 nike

感觉很简单,但没有用。我在这里错过了一些非常基本的东西吗?这些getter和setter方法在AppData类中,该类具有一个静态字段:List(元素类型LatLng)_navRoute = List();由于某种原因,get总是返回null。

static void setNewRoute() async{
List<LatLng> navRoute = await _googleMapPolyline.getCoordinatesWithLocation(
origin: LatLng(_currentLocation.latitude, _currentLocation.longitude),
destination: LatLng(_navDestination.latitude, _navDestination.longitude),
mode: RouteMode.walking
);
_navRoute = navRoute;
print("Nav route in set route is:" + _navRoute.toString()); //does not print null
}

static List<LatLng> getNavRoute(){
print("Nav route in get route is:" + _navRoute.toString()); //prints null
return _navRoute; //returns null
}

我调用这些函数的方式是:
onPressed: (){
setState(() {
AppData.updateCurrentLocation();
AppData.setNavDestination(widget._latitude, widget._longitude);
AppData.setNewRoute();
AppData.setNavStatus(true);
});
print("Current location is: " + AppData.getCurrentLocation().latitude.toString() + " , " + AppData.getCurrentLocation().longitude.toString()); //Not null
print("Nav destination is: " + AppData.getNavDestination().latitude.toString()+ ", " + AppData.getNavDestination().longitude.toString()); //Not null
print("Nav is: " + AppData.getNavRoute().toString()); //Always null
Navigator.pop(context); //pop the bottomModalSheet
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (BuildContext context) => AppData.getTour(widget._tourID),
),
);
},
),

最佳答案

这里有几个问题。

首先,您的async方法应返回Future,因为所有async方法都应返回Future:

static Future<void> setNewRoute() async{
...
}

其次,您需要对 await进行 Future:

onPressed: (){
setState(() async {
AppData.updateCurrentLocation();
AppData.setNavDestination(widget._latitude, widget._longitude);
// This will complete once you've actually set _navRoute
await AppData.setNewRoute();
AppData.setNavStatus(true);
});
print("Current location is: " + AppData.getCurrentLocation().latitude.toString() + " , " + AppData.getCurrentLocation().longitude.toString()); //Not null
print("Nav destination is: " + AppData.getNavDestination().latitude.toString()+ ", " + AppData.getNavDestination().longitude.toString()); //Not null
print("Nav is: " + AppData.getNavRoute().toString()); //Always null
Navigator.pop(context); //pop the bottomModalSheet
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (BuildContext context) => AppData.getTour(widget._tourID),
),
);
},
),

基本上 AppData.getNavRoute返回 null,因为实际上尚未设置 _navRoute,因为您没有等待它依赖的异步操作完成。

关于flutter - Dart:即使在调用异步Setter之后,Getter也会返回null(确保该方法中的字段不为null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59795112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com