flutterpostgoogle-apihttp-postgoogle-routes-api

Cast Error during HTTP Post Request to Google Route API,


This is the first time I am trying to use an HTTP Rest API with Post request, I am trying to use google Route API to compute direction, I follow the body from the google documentation however I keep getting this error _CastError

Exception has occurred. _CastError (type '_Map<String, Map<String, Map<String, double>>>' is not a subtype of type 'String' in type cast)

This is the first time I am trying a post request so I have no idea what is wrong here' the code I use

import 'dart:async';
import 'dart:ffi';

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'dart:convert' as convert;

class RouteAPI {
  final String key = 'API_KEY_HERE';
  Future<Void> getRoute() async {
    final String Url =
        'https://routes.googleapis.com/directions/v2:computeRoutes?KEY=$key';
    var response = await http.post(Uri.parse(Url), body: {
      "origin": {
        "location": {
          "latLng": {
            "latitude": -6.2425120808113315,
            "longitude": 106.85152720596324
          }
        },
      },
      "destination": {
        "location": {
          "latLng": {
            "latitude": -6.2425120808113315,
            "longitude": 106.85152720596324
          }
        },
      },
      "intermediates": {
        "location": {
          "latLng": {
            "latitude": -6.178359098658539,
            "longitude": 106.79219133887105
          }
        },
      },
      "travelMode": "DRIVE",
      "routingPreference": "TRAFFIC_AWARE",
      "polylineQuality": "HIGH_QUALITY",
      "polylineEncoding": "ENCODED_POLYLINE",
      //"departureTime": "",
      "computeAlternativeRoutes": "FALSE",
      "routeModifiers": {
        "avoidTolls": false,
        "avoidHighways": false,
        "avoidFerries": false
      },
      "languageCode": "en-US",
      "units": "IMPERIAL"
    });
    var json = convert.jsonDecode(response.body);
    print(json.toString());
    return json;
  }
}

I tried to send a post body to request an encoded polyline from google route API


Solution

  • Don't include API keys directly in your project, use environment variables, once someone has your API key, this can end bad with a lot of debt. Make sure you reset your key. flutter_dotenv.

    You also need to include your API key in your request header, from what I read. Compute a route docs

    You're receiving a type error because you're not encoding your body JSON into a string.

    convert.jsonEncode({"example": "example"})
    

    You then aren't setting the content type header to let the API know what kind of data you're sending, and the API Key, along with the field mask header.

    headers: {
    "Content-Type": "application/json",
    "X-Goog-Api-Key": "API_KEY",
    "X-Goog-FieldMask": "routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline"};
    

    I've replaced your response section for you.

    var response = await http.post(Uri.parse(url),
      body: convert.jsonEncode({
        "origin": {
          "location": {
            "latLng": {
              "latitude": -6.2425120808113315,
              "longitude": 106.85152720596324
            }
          },
        },
        "destination": {
          "location": {
            "latLng": {
              "latitude": -6.2425120808113315,
              "longitude": 106.85152720596324
            }
          },
        },
        "intermediates": {
          "location": {
            "latLng": {
              "latitude": -6.178359098658539,
              "longitude": 106.79219133887105
            }
          },
        },
        "travelMode": "DRIVE",
        "routingPreference": "TRAFFIC_AWARE",
        "polylineQuality": "HIGH_QUALITY",
        "polylineEncoding": "ENCODED_POLYLINE",
        //"departureTime": "",
        "computeAlternativeRoutes": "FALSE",
        "routeModifiers": {
          "avoidTolls": false,
          "avoidHighways": false,
          "avoidFerries": false
        },
        "languageCode": "en-US",
        "units": "IMPERIAL"
      }),
      headers: {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": "API_KEY",
        "X-Goog-FieldMask": "routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline"
      });