Http Connections And Retries

One of the most common activities in a mobile app is making HTTP calls. To do this from Dart, we need to first download a package, then use the new APIs to retrieve data.

Http Package

Common Dart packages come from https://pub.dartlang.org and the package commonly used for HTTP calls is the http package.

In your Flutter application, go to pubspec.yaml, and under the dependencies tag add the http package as demonstrated:

dependencies:
  http: "^0.12.0"
  flutter:
    sdk: flutter

Or the current latest version as shown in the versions tab on the Dart package. When you save this file, your IDE or editor should run a get packages command, to automatically pull down this package for you.

Import Namespace

To use the package, you need to import it first.

import 'package:http/http.dart';

HTTP GET

You can retrieve data using an http GET command. This returns a Response object with the data inside.

Future<Response> _getData() {
  return get('https://jsonplaceholder.typicode.com/posts/1'); 
}

Creating a small function, you can display the returned value when called.

String _data = "";
void _refresh() async {
  var data = await _getData(); 
  setState(() {
    _data = data.body;
  });
}

HTTP POST

To send data, you use the POST command.

Future<Response> _postData() {
  return post('https://jsonplaceholder.typicode.com/posts/1', body: '{value:1}');
}

You can additionally add headers and encoding options via optional parameters.

Retries

Mobile applications are particularly prone to unreliable network connections, hence you will want to ensure you retry connections if they fail. The http_retry package is designed to handle these situations.

Add the package to your pubspec.yaml file.

dependencies:
  http_retry: ^0.1.1+3

And import the package.

import 'package:http_retry/http_retry.dart';

Retry Failed Connection

Expanding our previous example, you can wrap an HTTP client inside a RetryClient, and specify the amount of retries, among other options.

void _refresh() async {
  var client = new RetryClient(new Client(), retries: 3);
  var data = await client.get('https://jsonplaceholder.typicode.com/posts/1');
  client.close();
  setState(() {
    _data = data.body;
  });
}

By default, it will retry 3 times, you only need to specify if you wish to change this. The Retry will only happen on HTTP 503 error codes. If you wish to retry on other conditions you can specify the when or whenError properties.

Adding this parameter, show an example of retrying on an HTTP 404 error.

when: (BaseResponse response) { return response.statusCode == 404; }
Share on
© 2019 Adam Pedley