0

I am trying to fetch a simple JSON file from my HTTPS server in flutter web however, it doesn't fetch the JSON and simply prints :-

Error code: XMLHTTPRequest error

How do I fix this issue? Here's my code -

Future<List<GamesJSON>> fetch(String link) async {
    final res = await get(Uri.parse(link));
    if (res.statusCode == 200) {
      final data = json.decode(res.body);
      final rest = data;
      list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
          as List<GamesJSON>;
    } 
    return list;
  }
Arnav
  • 1,404
  • 2
  • 19
  • 38
  • Did you test the GET API on postman? It could be a CORS issue. – Muhammad Hussain Apr 07 '22 at 14:35
  • Try this: https://stackoverflow.com/questions/65630743/how-to-solve-flutter-web-api-cors-error-only-with-dart-code/66879350#66879350 – Balint Takacs Apr 07 '22 at 15:01
  • @MuhammadHussain yes it works fine on android and ios but issue is with flutter web. and I tried disabling cors, but it won't work – Arnav Apr 08 '22 at 13:02
  • If it works on android and ios, then it makes more sense to say it's a CORS issue, you need to allow CORS from your backend side. Looks less like a flutter issue. – Muhammad Hussain Apr 08 '22 at 20:47
  • However, the source I am calling from is not from my own server/backend – Arnav Apr 09 '22 at 07:41
  • This only fixes CORS on my localhost, but in production this solution doesn't work @MuhammadHussain – Arnav Apr 10 '22 at 12:33

1 Answers1

-1

You need to change this line

list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
          as List<GamesJSON>;

to this

List<GamesJSON> list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList();

theredboy
  • 92
  • 10