ola
ola

Reputation: 29

Dart make synchronous api call

I'm learning flutter and I want to call an api which returns json. Because HttpClient methods are async and I don't want to deal with Future to build my material app, I've used the sync.http library but when I test the following code :

var result = Map();
try {
  final apiUri = Uri.parse('https://api.quotable.io/random');
  var request = SyncHttpClient.getUrl(apiUri);
  var response = request.close();
  var contents = response.toString();
  result = jsonDecode(contents);
}
on Exception {
  result['content'] = 'Could not contact host';
  result['author'] = 'None';
}
    return result;

I get the error :

Unhandled exception: Unsupported operation: unsupported http response format

I think this means that the json format isn't supported by the library but I find this weird. Do you know how I can call my api call synchronous ?

Upvotes: 1

Views: 1663

Answers (1)

Rohan Thacker
Rohan Thacker

Reputation: 6357

I'm not sure about the SyncHttp client from the docs it looks like an internal client used by flutter or the flutter team. I could be wrong but either way its not a good choice for a UI to have sync http requests.

Flutter provides a FutureBuilder Widget which will allow you to use async methods in the build method.

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FutureBuilder(
        future: fetchData(), // Your API Call here
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(''); // Your UI here
          } else if (snapshot.hasError) {
            return Text('Error');
          } else {
            return Text('Loading');
          }
        }
      ),
    );
  }

For more info and a performance tips visit

Flutter Widget of the Week - FutureBuilder

FutureBuilder Docs

Upvotes: 1

Related Questions