(flutter) Unhandled Exception: Null check operator used on a null value

  Kiến thức lập trình

I am developing simple map application
when I am trying to load polygon dat where stored in sharedpreferance and draw it with certain color, the error occurred as below,

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
#0 MapboxMapController.addFill (package:mapbox_gl/src/controller.dart:902:22)
#1 _MapScreenState._drawPolygon (package:worldvisitjongmin/mapscreen.dart:104:20)
#2 _MapScreenState._loadPolygons (package:worldvisitjongmin/mapscreen.dart:91:7)

the related code part is below


void _onMapCreated(MapboxMapController controller) {
  setState(() {
    mapController = controller;
  });
  _loadPolygons();  // 폴리곤 로드를 호출하는 위치
}

Future<void> _loadPolygons() async {
  // mapController가 초기화되지 않았다면 함수를 종료
  if (mapController == null) {
    print("Map controller is not initialized.");
    return;
  }

  final prefs = await SharedPreferences.getInstance();
  print("Loading polygon data...");
  try {
    for (String key in prefs.getKeys()) {
      if (!key.startsWith("polygon_")) continue;
      var data = prefs.getStringList(key);
      if (data != null && data.length > 1) {
        String fillColor = data[0];
        List<List<LatLng>> polyCoordinates = data.sublist(1).map((ring) {
          return ring.split(';').map((coord) {
            var latLng = coord.split(',');
            return LatLng(double.parse(latLng[0]), double.parse(latLng[1]));
          }).toList();
        }).toList();

        // 여기서 폴리곤을 그립니다.
        _drawPolygon(polyCoordinates, fillColor);
      }
    }
  } catch (e) {
    print("Error loading polygons: $e");
  }
}


void _drawPolygon(List<List<LatLng>> polyCoordinates, String fillColor) {
  if (mapController == null) {
    print("Map controller is not initialized.");
    return;
  }

  if (polyCoordinates.isEmpty) {
    print("polyCoordinates is empty, cannot draw polygon.");
    return;
  }

  print("Attempting to draw polygon with color $fillColor and coordinates $polyCoordinates");

  try {
    print("Trying to add polygon with color $fillColor");
    mapController!.addFill(FillOptions(
      geometry: polyCoordinates,
      fillColor: fillColor,
      fillOpacity: 0.5,
    ));
    print("Polygon drawn on map with color $fillColor.");
  } catch (e) {
    print("Failed to draw polygon on map: $e");
    print("Error details: $e");
    print("Polygon coordinates: $polyCoordinates");
  }
}

the result of debugging when the roading the data is below;

Xcode build done. 15.4s
flutter: Attempting to load GeoJSON data…
MGLMapView WARNING UIViewController.automaticallyAdjustsScrollViewInsets is deprecated use MGLMapView.automaticallyAdjustContentInset instead.
[CoreLocation] This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the -locationManagerDidChangeAuthorization: callback and checking authorizationStatus first.
[CoreLocation] This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the -locationManagerDidChangeAuthorization: callback and checking authorizationStatus first.
Installing and launching… 16.8s
flutter: Loading polygon data…
flutter: Polygon drawn on map with color #FFFF00.
flutter: Polygon drawn on map with color #90EE90.
flutter: Polygon drawn on map with color #FFFF00.
flutter: Polygon drawn on map with color #FFFF00.
flutter: Polygon drawn on map with color #87CEEB.
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
#0 MapboxMapController.addFill (package:mapbox_gl/src/controller.dart:902:22)
#1 _MapScreenState._drawPolygon (package:worldvisitjongmin/mapscreen.dart:104:20)
#2 _MapScreenState._loadPolygons (package:worldvisitjongmin/mapscreen.dart:91:7)

I don’t know how to solve this problem. plz help me!
Thanks in advance

I tried to load polygon after mapcreating set up is done like below

void _onMapCreated(MapboxMapController controller) {
  setState(() {
    mapController = controller;
  });
  _loadPolygons();  
}```


but still same errors 

New contributor

JONGMIN KIM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT