Muhammad Shafique
Muhammad Shafique

Reputation: 609

How to solve Error: XMLHttpRequest error. in Flutter Web

I want to use to Google places api and I am trying to call this api but I am getting this. error

Error: XMLHttpRequest error.
static Future<List<Result>?> searchPlaces(context, String query) async {
    String mapApiKey = "API_KEY";
    String _host = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
    final url = '$_host?query=$query&key=$mapApiKey';
    //
    var response = await http.get(Uri.parse(url));
    print(response.body);
    //
    if (response.statusCode == '200') {
      GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
      return result.results!;
    } else
      return null;
  }
}

Upvotes: 0

Views: 5837

Answers (2)

Muhammad Shafique
Muhammad Shafique

Reputation: 609

  1. Use this url 'https://cors-anywhere.herokuapp.com' before your actual url e.g.
String baseUrl = 'https://cors-anywhere.herokuapp.com';
String actualUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
String finalUrl = "$baseUrl/$actualUrl";

static Future<List<Result>?> searchPlaces(context, String query) async {
    String mapApiKey = "YOUR_KEY_HERE";
    var _sessionToken = Uuid().v4();
    String _host =
        'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json';
    final url = '$_host?query=$query&key=$mapApiKey';
    //
    var response = await http.get(Uri.parse(url);

    //
    GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
    return result.results!;
  }
}

Upvotes: -1

Ahmed Adel
Ahmed Adel

Reputation: 354

I don't know which platform you are using, but I guess the solution would be to disable chrome web security.

If you are working on mac try the following steps

  • Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
  • Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
  • Find '--disable-extensions'
  • Add '--disable-web-security'

And if you are working on windows just search for how to disable web security for chrome

Upvotes: 5

Related Questions