DEV Community

BC
BC

Posted on

5 1

Use dio in Flutter / Dart

We use dart's built-in HttpClient to call HTTP API:

HttpClient httpClient = HttpClient();
HttpClientRequest request = await httpClient.getUrl(uri);
// ...
Enter fullscreen mode Exit fullscreen mode

But using dio to do so is much easier. If you are Python developer, thinking this as the built-in urllib vs the requests lib. The latter one is much easier to use.

Let's do a quick demo of using thsi dio package.

1, Create a folder named "diotest", then create the pubspec.yaml file:

name: diotest
environment:
  sdk: '>=2.10.0 <3.0.0'
Enter fullscreen mode Exit fullscreen mode

2, Install the dio package:

$ dart pub add dio
Enter fullscreen mode Exit fullscreen mode

3, Create main.dart and write code like this:

import 'package:dio/dio.dart';

void main() async {
  BaseOptions options = BaseOptions(
    baseUrl: "https://httpbin.org",
    connectTimeout: 3000,
    receiveTimeout: 3000,
  );
  Dio dio = Dio(options);
  try {
    Response resp = await dio.get(
      "/get",
      queryParameters: {"search": "dio"},
    );
    print("Response:");
    print("Status:\n${resp.statusCode}");
    print("Header:\n${resp.headers}");
    print("Data:\n${resp.data}");
  } catch (e) {
    print("Exception: $e");
  }
}
Enter fullscreen mode Exit fullscreen mode

All set, now just run it:

$ dart main.dart
Response:
Status:
200
Header:
connection: keep-alive
access-control-allow-credentials: true
date: Fri, 17 Dec 2021 04:50:26 GMT
access-control-allow-origin: *
content-length: 306
content-type: application/json
server: gunicorn/19.9.0

Data:
{args: {search: dio}, headers: {Accept-Encoding: gzip, Host: httpbin.org, User-Agent: Dart/2.14 (dart:io), X-Amzn-Trace-Id: Root=1-61bc1712-57909160379aeca870fa551c}, origin: 67.83.137.85, url: https://httpbin.org/get?search=dio}
Enter fullscreen mode Exit fullscreen mode

For more on sending POST / PUT / DELETE / Upload Files, you can just visit the example page

Reference

Top comments (0)

AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️