android - Flutter "The getter 'latitude' was called on null" when using GeoLocator
问题描述
I am trying to get the position of a user. I am using GeoLocator and google_maps_flutter dependencies to do this.
When building I get an error for a split second when switching from the login screen to the google map screen. The error I am seeing in the console is...
The following NoSuchMethodError was thrown building googleMaps(dirty, state: MapAppState#bc232):
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude
My code is..
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,
),
),
);
}
}
I seen someone suggested using FutureBuilder but I do not believe I would like to take this route for fixing the error. Could someone point me in the right direction for fixing this error?
Thanks in advance!
解决方案
当您调用 getLocation() 时,它不会在阻塞庄园中被调用。因此,当创建 GoogleMap 小部件时,颤动事件循环尚未收到位置。对此的快速解决方法是在 getLocation() 之前调用 await。不幸的是,这会使屏幕加载时间变慢。一个更持久的修复方法是将 _initalPosition 设置为预定的 LatLng 或将用户的最后位置保存在 sharedPreferences 中并将其设置为该值以开始。这样,UI 仍然可以快速加载,并且 setState() 调用可以稍后更新 UI。
推荐阅读
- javascript - .click() 函数不让控件进入函数体
- ionic-framework - 使用相机后画布不更新(Android / Ionic)
- java - 为什么某些方法抛出的异常不需要处理
- sql - 使用单行字符串创建视图
- c - 如何优化此代码?斐波那契素数代码?
- docker - 为什么 docker push 证书文件上的注册表错误?
- r - 查找位于其他 DataFrame 上的两列值之间的 DataFrame 的值
- python - 如何跨函数视图和 CBV 传递 ID?- 姜戈
- kubernetes - 在 kubernetes/docker swarm 中部署 mariadb galera 集群
- css - 使用 vue-material,如何在列表中进行文本换行而不是溢出到省略号?