Dart:getter 被调用为 null。空检查后立即

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

我有一段代码如下所示:

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

我有时(通过 Sentry 错误捕获)收到以下错误:

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

我正在努力理解如何在 != null 检查后的行中出现“called on null”错误。

我不知道如何始终如一地重现错误。
我只是想知道理论上如何可能的答案。

mapController 变量是来自 flutter_map 库的 MapController class。

始终密切关注堆栈跟踪中的细节。在你的情况下,它说:

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

空指针异常来自MapControllerImpl。扫一眼 package:flutter_map 的代码,MapControllerImpl 来自包,而不是你的代码。 The referenced line 似乎是:

  LatLng get center => _state.center;

因此 MapControllerImpl 的内部 _state 变量为空。我不熟悉 package:flutter_map,但您可能应该先检查 mapController.ready(或以其他方式确保其 state 已设置)。