[英]i have been using reverse geocoding api and then i got this error?
E/flutter (23931): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未處理異常: RangeError (index): 無效值: 有效值范圍為空: 0
import 'package:geolocator/geolocator.dart';
import 'package:rider_app/Assistants/resquestAssitant.dart';
import 'package:rider_app/configMaps.dart';
class AssistantMethods {
static Future<String> searchCoordinateAddress(Position position) async {
String placeAddress = "";
String url = "https://maps.googleapis.com/maps/api/geocode/json? latlng=${position.latitude},${position.longitude}&key=$code";
var response = await RequestAssistant.getRequest(url);
if (response != "failed") {
placeAddress = response["results"][0]["formatted_address"];
}
return placeAddress;
}
}
這意味着 API 沒有返回結果,您正在無條件地訪問response["results"][0]
,但它可以並且在您的情況下確實沒有返回任何結果。
您應該檢查它是否不為空並且它們確實是結果列表,然后訪問 index[0]。
例如,如果您傳遞坐標,則可能會發生此結果,但 Google 無法解釋為地點或人類可讀的地址。 如果您在模擬器上,或者分配位於大西洋中部的隨機起始LatLng(0.0,0.0)
,則會發生很多情況。 我以前做過類似的事情。 或者基本上任何其他不讓 Google 返回響應的原因,如果您對 API 設置速率限制,或者陷入無限循環,最終暫時限制您的 API 請求的速率。 先檢查那些。
將您的 if 語句更改為:
if (response != "failed" && response["results"].isNotEmpty ) {
placeAddress = response["results"][0]["formatted_address"];
}else{
placeAddress = "Error in retrieving address info";}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.