Как удалить исключение Null на тематической карте и стоит ли оно того?

У меня есть картографическое приложение, которое использует пакет google_map_flutter и отображает тематическую карту в полноэкранном режиме. Меня беспокоит то, что когда я создаю приложение, я получаю необработанное исключение для setMapStyle, даже если карта отображается с темой.

Необработанное исключение: NoSuchMethodError: метод setMapStyle был вызван с нулевым значением. E / flutter (30877): Получатель: null E / flutter (30877): Пробный вызов: setMapStyle ("[\ r \ n {\ r \ n \" featureType \ ": \" Landscape \ ", \ r \ n \ "elementType \": \ "geometry \", \ r \ n .......

Тема представляет собой файл json, который я загружаю с помощью кода в моем initState ниже.

@override
  void initState() {
    super.initState();
    // Show the campus Map
    getSunData();
    // _showCampusMap();
    WidgetsBinding.instance.addObserver(this);
    // Check location permission has been granted

    PermissionHandler()
        .checkPermissionStatus(PermissionGroup
            .locationWhenInUse) //check permission returns a Future
        .then(_updateStatus); // handling in callback to prevent blocking UI

    rootBundle
        .loadString('assets/themes/map/day/simple_bright.json')
        .then((string) {
      mapStyle = string;
    });

    getUserLocation();
  }

Мой метод настройки стиля здесь.

// method that is called on map creation and takes a MapController as a parameter
  void _onMapCreated(GoogleMapController controller) async {
    PermissionHandler()
        .checkPermissionStatus(PermissionGroup
            .locationWhenInUse) //check permission returns a Future
        .then(_updateStatus); // handling in callback to prevent blocking UI

    controller.setMapStyle(mapStyle);
  }

Вот мой код GoogleMap

_userLocation == null
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          CircularProgressIndicator(
                            backgroundColor: Theme.UniColour.primary[900],
                          ),
                          SizedBox(height: 20.0),
                          Text("Retrieving your location..."),
                        ],
                      ),
                    )
                  : GoogleMap(
                      onMapCreated: _onMapCreated,
                      initialCameraPosition: // required parameter that sets the starting camera position. Camera position describes which part of the world you want the map to point at.
                          CameraPosition(
                              target: _userLocation,
                              zoom: _defaultZoom,
                              tilt: _tiltAngle), //LatLng(53.467125, -2.233966)
                      scrollGesturesEnabled: _scrollGesturesEnabled,
                      tiltGesturesEnabled: _tiltGesturesEnabled,
                      compassEnabled: _compassEnabled,
                      rotateGesturesEnabled: _rotateGesturesEnabled,
                      myLocationEnabled: _myLocationEnabled,
                      buildingsEnabled: _buildingsEnabled, // not added to db
                      indoorViewEnabled: _indoorViewEnabled, // not added to db
                      mapToolbarEnabled: _mapToolbarEnabled, // not added to db
                      myLocationButtonEnabled:
                          _myLocationButtonEnabled, // not added to db
                      mapType: _currentMapType,
                      zoomGesturesEnabled: _zoomGesturesEnabled,
                      cameraTargetBounds: CameraTargetBounds(
                        new LatLngBounds(
                          northeast: uniCampusNE,
                          southwest: uniCampusSW,
                        ),
                      ),
                      minMaxZoomPreference:
                          MinMaxZoomPreference(_minZoom, _maxZoom),
                    ),

Есть идеи, почему возникает это исключение, нужно ли его исправлять и как мне это сделать?

[РЕДАКТИРОВАТЬ]

void _updateStatus(PermissionStatus status) {
    if (status != _status) {
      // check status has changed
      setState(() {
        _status = status; // update
        _onMapCreated(controller);
      });
    } else {
      if (status != PermissionStatus.granted) {
        //print("REQUESTING PERMISSION");
        PermissionHandler().requestPermissions(
            [PermissionGroup.locationWhenInUse]).then(_onStatusRequested);
      }
    }
  }

Тип аргумента «Завершитель» нельзя присвоить типу параметра «GoogleMapController».

[/РЕДАКТИРОВАТЬ]

Благодарность


person Andrew Stevenson    schedule 29.01.2020    source источник


Ответы (1)


Вам нужно инициализировать класс Completer, под вашим классом State напишите следующее:

 Completer<GoogleMapController> _controller = Completer();

Затем используйте переменную _controller при вызове setMapStyle:

  void _onMapCreated(GoogleMapController controller) async {
    PermissionHandler()
        .checkPermissionStatus(PermissionGroup
            .locationWhenInUse) //check permission returns a Future
        .then(_updateStatus); // handling in callback to prevent blocking UI

   _controller.setMapStyle(mapStyle);
  }
person Peter Haddad    schedule 29.01.2020
comment
Спасибо, Питер, это влияет на мое разрешение _updateStatus. Я попытался заменить контроллер на _controller, но ошибка осталась. См. Мою правку выше. - person Andrew Stevenson; 29.01.2020
comment
в setState (в методе _updateStatus) _onMapCreated (контроллер); - person Andrew Stevenson; 29.01.2020
comment
вы меняли то, что передаете методу onMapCreated ?! - person Peter Haddad; 29.01.2020
comment
измените только переменную здесь _controller.setMapStyle(mapStyle); - person Peter Haddad; 29.01.2020
comment
Нет - я сохранил void _onMapCreated (контроллер GoogleMapController) async {то же самое, добавил Completer ‹GoogleMapController› _controller = Completer (); и измените controller.setMapStyle (mapStyle); в _controller.setMapStyle (mapStyle); - person Andrew Stevenson; 29.01.2020
comment
Я попытался переключить то, что я передал с контроллера на _controller - person Andrew Stevenson; 29.01.2020
comment
Внутри onmapcreated вам нужно передать контроллер типа GoogleMapController - person Peter Haddad; 29.01.2020
comment
Привет, Питер, я еще раз посмотрел на это и получаю сообщение об ошибке setMapStyle в строке - ›_controller.setMapStyle (_mapTheme); в моем методе onMapCreated. Я также передаю контроллер GoogleMapControler в onMapCreated. Я заметил эту строку - ›FutureOr ‹GoogleMapController› get controller =› null; который был добавлен VSCode. Я считаю, что отсюда и возникает нулевая ошибка. Использование Completer для меня просто не работает. Если у вас есть другие идеи, я был бы признателен. Спасибо за ваше время - person Andrew Stevenson; 03.02.2020