0

I have recently transferred a fully functioning app to dart null safety and it has thrown some errors

This API call has been adapted but now I am receiving the error flutter: Exception Happened: type 'String' is not a subtype of type 'Mode'

I call the API by a function which gains the user position to make the call.

To reiterate, this was working perfectly before upgrading dart so it's an issue of adapting to null safety I believe.

The API call (Where the exception is throwing)

Future<Stations?> fetchStations() async {
    var client = http.Client();
    Stations? stations; 
     
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);


    var lat = position.latitude;
    var long = position.longitude;
    
try{
    var response = await client.get(Uri.parse('https_call'));
    if (response.statusCode == 200) {
   var jsonString = response.body;
   var jsonMap = json.decode(jsonString);
   
   stations = Stations.fromJson(jsonMap);
   //print(stations);
  }
} catch(e) {

  print("Exception Happened: ${e.toString()}");
}
 
  return stations; 
}

The function to call API

Future<void> showAnchoredMapMarkers() async {
  var stations = await fetchStations();
  for (Station stations in stations!.stations) {
    GeoCoordinates geoCoordinates = GeoCoordinates (stations.place.location.lat, stations.place.location.lng);
    var id = stations.place.id;
    
    _addCircleMapMarker(geoCoordinates, 0);
    _addPOIMapMarker(geoCoordinates, 1);
  
  }
}

Update

class Station {
    Station({
        this.place,
        required this.transports,
    });

    Place place;
    List<Transport> transports;

    factory Station.fromJson(Map<String, dynamic> json) => Station(
        place: json["place"] == null ? null : Place.fromJson(json["place"]),
        transports: json["transports"] == null ? null : List<Transport>.from(json["transports"].map((x) => Transport.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "place": place == null ? null : place.toJson(),
        "transports": transports == null ? null : List<dynamic>.from(transports.map((x) => x.toJson())),
    };
}

The lines such as

place: json["place"] == null ? null : Place.fromJson(json["place"]),

are all red underlined with errors such as

The argument type 'Place?' can't be assigned to the parameter type 'Place'.
al246
  • 220
  • 6
  • 16

1 Answers1

1

This is happening because in your Model file you have defined value of mode should be a Mode but you are passing a String to it. Simple solution is to change datatype of the mode to String like below :

class Transport {
    Transport({
        required this.mode,
        required this.name,
        required this.color,
        required this.textColor,
        required this.headsign,
    });

    String mode;
    String name;
    String color;
    TextColor textColor;
    String headsign;

   more code ...
}
Diwyansh
  • 2,961
  • 1
  • 7
  • 11
  • Thank you, that has seemed to fix that specific instance, I now receive this exception instead ```flutter: Exception Happened: type 'Null' is not a subtype of type 'String'``` Do you know why this is? Thanks – al246 Jan 05 '22 at 17:04
  • This is because may be you are getting null value from the API and your model is not ready for that. You can solve this by making that variable nullable like String? just put ? mark and your error should get resolved. – Diwyansh Jan 05 '22 at 17:06
  • It appears to be coming from the line ```for (Station stations in stations!.stations) {``` in the function to call the API. Error is ```_CastError (Null check operator used on a null value)```. I had to add a ```!``` to fix red underline on ```stations```, this must be the cause somehow? Thanks – al246 Jan 05 '22 at 17:12
  • It means that you are not getting the value in stations, you need to check for it. – Diwyansh Jan 05 '22 at 17:14
  • I call the api in internet browser and it returns the data fine. My confusion is because it worked perfectly before ```null safety```. I have now just called the ```fetch stations``` method to see what comes back and nothing is, is it because of the json adaptations i've made (required etc) – al246 Jan 05 '22 at 17:16
  • Try printing stations that you are getting data or not. – Diwyansh Jan 05 '22 at 17:21
  • I have printed it, no data returns and I get the exception ```NoSuchMethodError: The method 'map' was called on null.``` in addition after I ```?``` all the ```String``` options in the Json model – al246 Jan 05 '22 at 17:24
  • do one thing make a new Model using https://app.quicktype.io/ and there's a button in option Make all properties optional enabled that and paste it to your file after that you also need to make variables nullable using ? like String? int?. I think this may solve your error – Diwyansh Jan 05 '22 at 17:26
  • Even if your problem doesn't solves then please share a sample json. – Diwyansh Jan 05 '22 at 17:27
  • Thank you, I have updated my Json but many of the lines, I think ones that aren't ```String```, are all red underlined and I can't null them with a ? like I can the ```String```. I have added *update* to my main question^ with example and details. Thanks – al246 Jan 05 '22 at 17:38
  • make them nullable as well like Place? & List? transports; – Diwyansh Jan 05 '22 at 17:42
  • I now receive ```Instance of 'Stations'```, and have added null safety to lots of places and it seems to be on its way to working! Error ```LateError (LateInitializationError: Field '_circleMapImage@18029483' has not been initialized.)``` now shows and I'm not sure how to initialise it? It should be an image in my ```asset``` folder – al246 Jan 05 '22 at 17:58
  • Initializing means that you have to assign some value to the variable that you have defined. After doing so if your issues resolved then mark this question as answered. – Diwyansh Jan 05 '22 at 18:01