I'm making HTTP Requests in Flutter with following code to find the nearest city by lat/lng:
import 'package:http/http.dart' as HTTP;
import 'dart:convert';
import 'dart:developer';
import 'package:myApp/models/city.dart';
class API {
static Future<Map<String, dynamic>> call(Map<String, dynamic> data) async {
return await HTTP.post(Uri.parse('https://myapp.de/api/'),
headers: <String, String>{
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8",
"User-Agent": "myApp/1.0.0 (Android)"
},
body: jsonEncode(data),
).then((response) {
try {
return jsonDecode(response.body) as Map<String, dynamic>;
} catch(e) {
log("[API] JSON Exception: $e");
return <String, dynamic>{};
}
}).onError((error, stackTrace) {
log("[API] $error: $stackTrace");
return <String, dynamic>{};
});
}
static Future<City> getCity(double longitude, double latitude) async {
return await call(<String, dynamic>{
"action": "city",
"longitude": longitude,
"latitude": latitude
}).then((data) {
return CityResponse.fromJson(data).first();
});
}
}
The HTTP Request has following Request & Response: Request
{
"action": "city",
"longitude": 8.5122942,
"latitude": 50.5141822
}
Response
{
"status": true,
"result": [
{
"name": "Reiskirchen",
"country": "DE",
"longitude": "8.51046",
"latitude": "50.50404",
"distance": 0.704886732081551
}
]
}
And here is the city class:
class City {
final String name;
final String country;
final String longitude;
final String latitude;
final double distance;
City(
this.name,
this.country,
this.longitude,
this.latitude,
this.distance
);
City.fromJson(Map<String, dynamic> json) :
name = json['name']! as String,
country = json['country']! as String,
longitude = json['longitude']! as String,
latitude = json['latitude']! as String,
distance = json['distance']! as double;
Map<String, dynamic> toJson() => {
'name': name,
'country': country,
'longitude': longitude,
'latitude': latitude,
'distance': distance,
};
}
class CityResponse {
final bool status;
final List<City> result;
CityResponse(
this.status,
this.result,
);
CityResponse.fromJson(Map<String, dynamic> json) :
status = json['status'] as bool,
result = (json['result'] as List).map((entry) => City.fromJson(entry)).toList();
Map<String, dynamic> toJson() => {
'status': status,
'result': (result).map((entry) => entry.toJson()).toList()
};
City first() {
return result[0];
}
}
An example call will be inited by:
await API.getCity(data.longitude!, data.latitude!);
The problem I have is that I keep getting an indeterminate exception:

I had already tried to add explicit null-ignore-check by using ? or !like
json['status']! as bool
How can I fix the problem?
In my opinion, it may also be related to the server, which unexpectedly delivers disconnects (ERR_CONNECTION_TIMED_OUT) because the hoster dreamhost.com is poorly connected to Germany.
How can I avoid this behavior by checking?
!,?or??i get the same errorbool.tryParse(json['status']) ?? false