Search code examples
flutterdartpostman

GET API call failing in http Dart but working in Postman


I am trying to make a basic GET request in flutter using http package. Although I tried it multiple times while debugging it does not work, meanwhile making the same http request in Postman DOES work. What could be the reason?

This is the method I am using. Debugger stops working before entering the "try" statement.

  getCoordinatesFromPlaceId(String placeId) async {
    var client = http.Client();

    var url_coord =
        'https://maps.googleapis.com/maps/api/place/details/json?fields=geometry&place_id=$placeId&key=APIKEY';
    var response = await client.get(
      Uri.parse(url_coord),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );

    try {
      var jsonResponse = json.decode(response.body);
      
    } catch (e) {
      print(e);
    }
  }

You can see the result in Postman:

enter image description here


Solution

  • static Future<dynamic?> getApiData() async {
        String url='https://maps.googleapis.com/maps/api/place/details/json?fields=geometry&place_id=$placeId&key=APIKEY';
        try {
          var response = await http.get(
            Uri.parse(url),
            headers: <String, String>{
              'Content-Type': 'application/json; charset=UTF-8',
            },
          );
          if (response.statusCode == 200) {
            var jsonResponse = json.decode(response.body);
          } else {
            return null;
          }
        } catch (e) {
          return null;
        }
      }