调用Google Route API发送HTTP Post请求时遇_CastError问题求助
问题排查与修复方案
核心错误原因
你遇到的_CastError是因为请求体格式不匹配:http.post方法直接传入Map时,默认会把请求编码为application/x-www-form-urlencoded格式,但Google Routes API要求的是application/json格式的请求体,导致API无法解析你的请求,同时Dart内部也会因为格式转换失败抛出类型转换错误。
具体修复步骤
- 将请求体转为JSON字符串:使用
convert.jsonEncode()把Map转为JSON格式的字符串,作为body参数传入。 - 设置正确的请求头:添加
Content-Type: application/json头,告知API请求体的格式。 - 修正其他参数错误:
Future<Void>改为Future<Map<String, dynamic>>(或dynamic),因为你返回的是JSON对象,不是Void。intermediates是数组类型(官方文档中该字段支持多个途经点),你当前传的是单个对象,需要改成列表[]包裹。computeAlternativeRoutes应该是布尔值false,不是字符串"FALSE"。
修正后的完整代码
import 'dart:async'; 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<Map<String, dynamic>> getRoute() async { final String url = 'https://routes.googleapis.com/directions/v2:computeRoutes?key=$key'; // 构造请求体Map final requestBody = { "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", "computeAlternativeRoutes": false, // 修正为布尔值 "routeModifiers": { "avoidTolls": false, "avoidHighways": false, "avoidFerries": false }, "languageCode": "en-US", "units": "IMPERIAL" }; var response = await http.post( Uri.parse(url), body: convert.jsonEncode(requestBody), // 转为JSON字符串 headers: { // 设置请求头 'Content-Type': 'application/json', }, ); if (response.statusCode == 200) { var json = convert.jsonDecode(response.body) as Map<String, dynamic>; print(json.toString()); return json; } else { // 处理请求失败场景 throw Exception('请求失败,状态码:${response.statusCode},响应内容:${response.body}'); } } }
额外说明
- 确保你的API Key已启用Google Routes API权限,否则会返回权限错误。
- 成功请求后,返回的JSON中
routes[0].polyline.encodedPolyline字段就是你需要的编码折线数据。
内容的提问来源于stack exchange,提问作者Flutter Beginner
相关产品推荐
相关产品推荐

