使用地理定位器时颤振"The getter 'latitude' was called on null"



我正在尝试获取用户的位置。我使用GeoLocator和google_maps_flutter依赖项来完成这项工作。

在构建时,从登录屏幕切换到谷歌地图屏幕时,我会在一瞬间出现错误。我在控制台中看到的错误是…

The following NoSuchMethodError was thrown building googleMaps(dirty, state: MapAppState#bc232):
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude

我的代码是..

class googleMaps extends StatefulWidget {
@override
MapAppState createState() => MapAppState();
}
class MapAppState extends State<googleMaps> {
GoogleMapController mapController;
Position position;
static LatLng _initialPosition;
static LatLng _lastMapPosition = _initialPosition;
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
void getLocation() async {
position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() {
_initialPosition = LatLng(position.latitude, position.longitude);
});
}
@override
Widget build(BuildContext context) {
getLocation();
return MaterialApp(
home: Scaffold(
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: 11.0,
),
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
new Factory<OneSequenceGestureRecognizer>(
() => new EagerGestureRecognizer(),
),
].toSet(),
cameraTargetBounds: CameraTargetBounds.unbounded,
minMaxZoomPreference: MinMaxZoomPreference.unbounded,
rotateGesturesEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
tiltGesturesEnabled: true,
myLocationButtonEnabled: true,
myLocationEnabled: true,
),
),
);
}
}

我看到有人建议使用FutureBuilder,但我不相信我会采取这种方法来修复错误。有人能为我指出纠正这个错误的正确方向吗?

提前感谢!

当您调用getLocation((时,它不会在阻塞庄园中被调用。因此,在创建GoogleMap小部件时,flutter事件循环尚未接收到位置。对此的快速修复方法是在getLocation((之前调用wait。不幸的是,这会使屏幕加载时间变慢。一个更持久的解决方案是将_initalPosition设置为预先定义的LatLng,或者将用户的最后一个位置保存在sharedPreferences中,并将其设置为该值。这样,UI仍然可以快速加载,并且setState((调用可以稍后更新UI。

getLocation()置于initState

相关内容

最新更新