首页 > 解决方案 > 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!

标签: androidflutterdart

解决方案


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


推荐阅读