To make the most of Flutter, developers need to use an HTTP client to make requests to web services and receive responses.
Developers often choose an HTTP client when they need to send and get data from APIs. Flutter is new but it is already gets supported by good HTTP clients.
http
http contains a variety of high-level functions and classes that make it easy to send and get an HTTP request and response. It supports multi-platform, including mobile, desktop, and web.
import 'package:http/http.dart' as http; var response = await http.get('https://jsonplaceholder.typicode.com/posts/1'); print(response);
dio
dio is a powerful HTTP client for Dart. It supports FormData, Request Cancellation, Interceptors, Global configuration, File downloading, Timeout, and more.
import 'package:dio/dio.dart'; void request() async { try { Response response = await Dio().get("https://jsonplaceholder.typicode.com/posts/"); print(response); } catch (e) { print(e); } }
There are many packages that make dio better.
Plugins | Description |
---|---|
dio_cookie_manager | A cookie manager for Dio |
dio_http2_adapter | A Dio HttpClientAdapter which supports Http/2.0 |
dio_flutter_transformer | A Dio transformer especially for flutter, by which the JSON decoding will be in the background with compute  function. |
dio_http_cache | A cache library for Dio, like Rxcache in Android. dio-http-cache uses sqflite as disk cache and LRU strategy as a memory cache. |
retrofit
retrofit, inspired by Chopper and Retrofit, is a dio client generator using source_gen.
import 'package:json_annotation/json_annotation.dart'; import 'package:retrofit/retrofit.dart'; import 'package:dio/dio.dart'; part 'example.g.dart'; @RestApi(baseUrl: "https://jsonplaceholder.typicode.com") abstract class RestClient { factory RestClient(Dio dio, {String baseUrl}) = _RestClient; @GET("/posts") Future<List<Post>> getPosts(); } @JsonSerializable() class Post { String userId; String id; String title; String body; Post({this.userId, this.id, this.title, this.body}); factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json); Map<String, dynamic> toJson() => _$PostToJson(this); }