kris
kris

Reputation: 12620

Dart : The getter was called on null. Immediately after null check

I have a piece of code that looks like this :

    if (mapController != null) {
      final LatLng oldLatLng = mapController.center;   // this is line 185 in stMapScreen.dart

I am sometimes (via Sentry error catching) getting the following error :

NoSuchMethodError: NoSuchMethodError: The getter 'center' was called on null.
Receiver: null
Tried calling: center
  File "map.dart", line 44, in MapControllerImpl.center
  File "stMapScreen.dart", line 185, in _StMapScreenState.glideToLocation

I'm struggling to understand how I can get a "called on null" error in the line after a != null check.

I don't know how to consistently reproduce the error.
I'm just asking for answers on how it's possible theoretically.

The mapController var is a MapController class from the flutter_map library.

Upvotes: 0

Views: 432

Answers (1)

jamesdlin
jamesdlin

Reputation: 90175

Always pay close attention to the details from the stack trace. In your case, it says:

NoSuchMethodError: NoSuchMethodError: The getter 'center' was called on null.
Receiver: null
Tried calling: center
  File "map.dart", line 44, in MapControllerImpl.center

The null pointer exception came from MapControllerImpl. Glancing at the code to package:flutter_map, MapControllerImpl comes from the package, not your code. The referenced line seems to be:

  LatLng get center => _state.center;

So MapControllerImpl's internal _state variable is null. I am not familiar with package:flutter_map, but possibly you should check mapController.ready first (or otherwise ensure that its state is set).

Upvotes: 3

Related Questions