0

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: 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?

5
  • have you checked the network monitor response and see if the status can be null? if thats the case maybe you can make it null or default it to false in that case: 'json['status'] as bool?' or '(json['status'] as bool?) ?? false' Commented Apr 11, 2024 at 22:21
  • The API doesnt return null values. Either an empty array is output or the city with the known data from the object. A null check wont work, with !, ? or ?? i get the same error Commented Apr 11, 2024 at 22:23
  • you have to checkyour response in your network monitor, it seems something is off, json is null or another type (not map maybe) Commented Apr 11, 2024 at 22:42
  • 1
    why don'y you use bool.tryParse(json['status']) ?? false Commented Apr 12, 2024 at 5:43
  • @Nagual because it will expect the same error? Commented Apr 12, 2024 at 17:24

1 Answer 1

-2

I dont found any error in the code maybe is in the api

a way to avoid null is this way

 CityResponse.fromJson(Map<String, dynamic> json) :
    status  = (json['status'] as bool) ?? false,
    result  = ((json['result'] as List) ?? []).map((entry) => City.fromJson(entry)).toList();
Sign up to request clarification or add additional context in comments.

2 Comments

Please read the question. I've already sayed, that i had already tried to add explicit null-ignore-checks. The error does not come from the API side. Either an empty array is output or the city with the known data from the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.