A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.
dependencies:
dio: 3.x #latest version
In order to support Flutter Web, v3.x was heavily refactored, so v3.x is not compatible with v2.x See the changelog for a detailed list of updates.
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.google.com");
print(response);
} catch (e) {
print(e);
}
}
🎉 A curated list of awesome things related to dio.
Plugins | Status | Description |
---|---|---|
dio_cookie_manager | A cookie manager for Dio | |
dio_http2_adapter | A Dio HttpClientAdapter which support Http/2.0 | |
dio_flutter_transformer | A Dio transformer especially for flutter, by which the json decoding will be in 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 memory cache. | |
retrofit | retrofit.dart is an dio client generator using source_gen and inspired by Chopper and Retrofit. | |
dio_firebase_performance | A Dio Interceptor for reporting network metrics to Firebase | |
postman_dio | A Dio Logger Interceptor for export to "Postman Collection".json |
Welcome to submit Dio's third-party plugins and related libraries here .
Performing a GET
request:
Response response;
Dio dio = new Dio();
response = await dio.get("/test?id=12&name=wendu");
print(response.data.toString());
// Optionally the request above could also be done as
response = await dio.get("/test", queryParameters: {"id": 12, "name": "wendu"});
print(response.data.toString());
Performing a POST
request:
response = await dio.post("/test", data: {"id": 12, "name": "wendu"});
Performing multiple concurrent requests:
response = await Future.wait([dio.post("/info"), dio.get("/token")]);
Downloading a file:
response = await dio.download("https://www.google.com/", "./xx.html");
Get response stream:
Response<ResponseBody> rs = await Dio().get<ResponseBody>(url,
options: Options(responseType: ResponseType.stream), // set responseType to `stream`
);
print(rs.data.stream); //response stream
Get response with bytes:
Response<List<int>> rs = await Dio().get<List<int>>(url,
options: Options(responseType: ResponseType.bytes), // // set responseType to `bytes`
);
print(rs.data); // List<int>
Sending FormData:
FormData formData = new FormData.fromMap({
"name": "wendux",
"age": 25,
});
response = await dio.post("/info", data: formData);
Uploading multiple files to server by FormData:
FormData.fromMap({
"name": "wendux",
"age": 25,
"file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt"),
"files": [
await MultipartFile.fromFile("./text1.txt", filename: "text1.txt"),
await MultipartFile.fromFile("./text2.txt", filename: "text2.txt"),
]
});
response = await dio.post("/info", data: formData);
Listening the uploading progress:
response = await dio.post(
"http://www.dtworkroom.com/doris/1/2.0.0/test",
data: {"aa": "bb" * 22},
onSendProgress: (int sent, int total) {
print("$sent $total");
},
);
Post binary data by Stream:
// Binary data
List<int> postData = <int>[...];
await dio.post(
url,
data: Stream.fromIterable(postData.map((e) => [e])), //create a Stream<List<int>>
options: Options(
headers: {
Headers.contentLengthHeader: postData.length, // set content-length
},
),
);
…you can find all examples code here.
You can create instance of Dio with an optional BaseOptions
object:
Dio dio = new Dio(); // with default Options
// Set default configs
dio.options.baseUrl = "https://www.xx.com/api";
dio.options.connectTimeout = 5000; //5s
dio.options.receiveTimeout = 3000;
// or new Dio with a BaseOptions instance.
BaseOptions options = new BaseOptions(
baseUrl: "https://www.xx.com/api",
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
The core API in Dio instance is:
Future request(String path, {data,Map queryParameters, Options options,CancelToken cancelToken, ProgressCallback onSendProgress, ProgressCallback onReceiveProgress)
response=await request(
"/test",
data: {"id":12,"name":"xx"},
options: Options(method:"GET"),
);
For convenience aliases have been provided for all supported request methods.
Future get(...)
Future post(...)
Future put(...)
Future delete(...)
Future head(...)
Future put(...)
Future path(...)
Future download(...)
The Options class describes the http request information and configuration. Each Dio instance has a base config for all requests maked by itself, and we can override the base config with [Options] when make a single request. The [BaseOptions] declaration as follows:
{
/// Http method.
String method;
/// Request base url, it can contain sub path, like: "https://www.google.com/api/".
String baseUrl;
/// Http request headers.
Map<String, dynamic> headers;
/// Timeout in milliseconds for opening url.
int connectTimeout;
/// Whenever more than [receiveTimeout] (in milliseconds) passes between two events from response stream,
/// [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT].
/// Note: This is not the receiving time limitation.
int receiveTimeout;
/// Request data, can be any type.
T data;
/// If the `path` starts with "http(s)", the `baseURL` will be ignored, otherwise,
/// it will be combined and then resolved with the baseUrl.
String path="";
/// The request Content-Type. The default value is "application/json; charset=utf-8".
/// If you want to encode request body with "application/x-www-form-urlencoded",
/// you can set [Headers.formUrlEncodedContentType], and [Dio]
/// will automatically encode the request body.
String contentType;
/// [responseType] indicates the type of data that the server will respond with
/// options which defined in [ResponseType] are `JSON`, `STREAM`, `PLAIN`.
///
/// The default value is `JSON`, dio will parse response string to json object automatically
/// when the content-type of response is "application/json".
///
/// If you want to receive response data with binary bytes, for example,
/// downloading a image, use `STREAM`.
///
/// If you want to receive the response data with String, use `PLAIN`.
ResponseType responseType;
/// `validateStatus` defines whether the request is successful for a given
/// HTTP response status code. If `validateStatus` returns `true` ,
/// the request will be perceived as successful; otherwise, considered as failed.
ValidateStatus validateStatus;
/// Custom field that you can retrieve it later in [Interceptor]、[Transformer] and the [Response] object.
Map<String, dynamic> extra;
/// Common query parameters
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters;
}
There is a complete example here.
The response for a request contains the following information.
{
/// Response body. may have been transformed, please refer to [ResponseType].
T data;
/// Response headers.
Headers headers;
/// The corresponding request info.
Options request;
/// Http status code.
int statusCode;
/// Whether redirect
bool isRedirect;
/// redirect info
List<RedirectInfo> redirects ;
/// Returns the final real request uri (maybe redirect).
Uri realUri;
/// Custom field that you can retrieve it later in `then`.
Map<String, dynamic> extra;
}
When request is succeed, you will receive the response as follows:
< 5D32 div class="highlight highlight-source-dart notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="Response response = await dio.get("https://www.google.com"); print(response.data); print(response.headers); print(response.request); print(response.statusCode);">Response response = await dio.get("https://www.google.com"); print(response.data); print(response.headers); print(response.request); print(response.statusCode);