这是我第一次try 使用带有POST请求的HTTP REST API,我try 使用Google Routing API来计算方向,我遵循Google文档中的正文,但我一直收到此错误 _CastError

已发生异常. _CastError(类型‘_Map<字符串,映射<字符串,映射<字符串,Double>>>’在类型转换中不是类型‘字符串’的子类型)

这是我第一次try POST请求,所以我不知道出了什么问题 以下是我使用的代码

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;
  }
}

我try 发送一个POST正文,从Google Route API请求一个编码折线

推荐答案

不要将API密钥直接包含在您的项目中,使用环境变量,一旦有人拥有您的API密钥,这可能会以一大笔债务结束.一定要重置你的 keys . flutter_dotenv.

据我所知,您还需要在请求头中包含您的API密钥.Compute a route docs

您收到一个类型错误,因为您没有将Body JSON编码为字符串.

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

然后,您不需要设置内容类型标头来让API知道您要发送的数据类型、API密钥以及字段掩码标头.

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

我已经替您更换了您的答复区.

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"
  });

Flutter相关问答推荐

如何在不使用NULL-check(!)的情况下缩小`FutureBuilder.Builder()`内部的`Snaphot`范围

Flutter -如何将导航轨道标签靠左对齐?

Flutter AppBar Animation反向调试

在框中保存对象列表时,类型推断无法正常工作

你能go 掉Flutter 小部件测试中的样板吗?

就像Flutter 中的头文件一样?

在Fighter中,我如何在窗口的顶部和底部排列Widget?

通过Ffltter应用程序与Docker服务器进行交互以进行身份验证

Flutter Android Google Sign-in error:ApiException:10在确认软件包名称、SHA-1 fingerprint 和设置同意页面后出现异常

StateNotifer正在riverpod中提供初始状态值(bool)

如何使用providerContainer监听/写入FutureProvider?

如何在 Flutter 中创建具有渐变背景色的自定义 Snackbar?

Flutter:注册 UI 出现 UI 问题(将注册框提升到顶部并向电话号码 pin 码添加一个框)

仅在获取(读取)、Provider 时,Firestore 中的数据为空

如何显示从 MariaDB 获取的数据到列表视图

Show Snackbar above to showModalBottomSheet Flutter

使用 Chaquopy 插件后 Gradle Sync 无法正常工作

如何在dart中编写多个条件?

在 Flutter 中,如何使用文本字段和方形图像进行行布局

在 Flutter 中单击时切换按钮 colored颜色 没有改变