Reputation: 21
E/flutter (23931): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 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;
}
}
Upvotes: 1
Views: 825
Reputation: 12373
This means that the API didn't return results, you are accessing response["results"][0]
unconditionally, but it can, and in your case did, actually not return any results.
You should check if it's not empty and that their is indeed a list of results, then access index[0].
This result could happen if you pass coordinates for example, but Google couldn't interpret into a place or human readable address. Happens a lot if you're on an emulator, or assign random starting LatLng(0.0,0.0)
which is in the middle of the Atlantic ocean. I've done similar things before. Or basically any other reason to not let Google return a response, if you set a rate limit on your API, or caught in an infinity loop that ends up temporarily rate limiting your API requests. Check those first.
Change your if statement to this:
if (response != "failed" && response["results"].isNotEmpty ) {
placeAddress = response["results"][0]["formatted_address"];
}else{
placeAddress = "Error in retrieving address info";}
Upvotes: 1