Christy Royo
Christy Royo

Reputation: 45

Flutter: http.get() Unhandled Exception: FormatException: Unexpected character (at character 1)

I'm creating a Flutter app and I'm trying to fetch my dummy data from this endpoint. I wanted to print the response data but my problem is upon fetching the API, the Content-Type is text/html instead of application/json. I'm using the HTTP package.

here's the error

here's my code method for base_api.dart

Future<MODEL> getAll() async {
  Map<String, String> headers = {"Content-type": "application/json"};
  final result = await http.get(url, headers: headers);
  print("Content type: ${result.headers['content-type']}");
  if (result.statusCode >= 200 && result.statusCode < 300 ) {
     return json.decode(result.body);
  } else {
     return json.decode(null);
  }                                                                                         
}

and here's my code in services.dart

Future loadUserTimeLogs() async {
  var userRepo = UserRepository();
  userRepo.getAll().then((val) {
    print("GET VAL: $val");
  }); }                                                                                  

and here's my base_repository.dart

Future getAll({String query}) {
 var completer = Completer();
 api.getAll().then((val) {
 if (val == null) {
    completer.complete(dao.getAll());
 } else {
    completer.complete(val);
 }
 });                                                                                     
 return completer.future;
}

Upvotes: 1

Views: 3451

Answers (2)

Simon Pham
Simon Pham

Reputation: 2023

try with this endpoint: http://www.mocky.io/v2/5dca69523300004e003decc5

and use this return json.decode(result.body)['data']; in your getAll() function

Upvotes: 0

Jian Astrero
Jian Astrero

Reputation: 742

It seems like it is working, have you checked if you have a stable internet connection or if you are connecting to a wifi that has restricted access? The HTML might be the captive portal or the restrict webpage from the wifi you are connected to.

Upvotes: 1

Related Questions