Need help with dio?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

9.2K Stars 972 Forks MIT License 288 Commits 49 Opened issues


A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

Services available


Need anything else?

Contributors list

Language: English | 中文简体


build status Pub support

A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

Get started

Add dependency

  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.

Super simple to use

import 'package:dio/dio.dart';
void getHttp() async {
  try {
    Response response = await Dio().get("");
  } catch (e) {


🎉 A curated list of awesome things related to dio.


| Plugins | Status | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | diocookiemanager | Pub | A cookie manager for Dio | | diohttp2adapter | Pub | A Dio HttpClientAdapter which support Http/2.0 | | diofluttertransformer | Pub | A Dio transformer especially for flutter, by which the json decoding will be in background with

function. | | diohttpcache | Pub | A cache library for Dio, like Rxcache in Android. dio-http-cache uses sqflite as disk cache, and LRU strategy as memory cache. | | retrofit | Pub | retrofit.dart is an dio client generator using sourcegen and inspired by Chopper and Retrofit. | | diofirebaseperformance | [Pub]( | A Dio Interceptor for reporting network metrics to Firebase | postman_dio | [Pub]( | A Dio Logger Interceptor for export to "Postman Collection".json |

Related Projects

Welcome to submit Dio's third-party plugins and related libraries here .

Table of contents


Performing a

Response response;
Dio dio = new Dio();
response = await dio.get("/test?id=12&name=wendu");
// Optionally the request above could also be done as
response = await dio.get("/test", queryParameters: {"id": 12, "name": "wendu"});

Performing a

response = await"/test", data: {"id": 12, "name": "wendu"});

Performing multiple concurrent requests:

response = await Future.wait(["/info"), dio.get("/token")]);

Downloading a file:

response = await"", "./xx.html");

Get response stream:

Response rs = await Dio().get(url,
 options: Options(responseType:, // set responseType to `stream`
print(; //response stream

Get response with bytes:

Response> rs = await Dio().get>(url,
 options: Options(responseType: ResponseType.bytes), // // set responseType to `bytes`
print(; // List

Sending FormData:

FormData formData = new FormData.fromMap({
    "name": "wendux",
    "age": 25,
response = await"/info", data: formData);

Uploading multiple files to server by FormData:

    "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"/info", data: formData);

Listening the uploading progress:

response = await
  data: {"aa": "bb" * 22},
  onSendProgress: (int sent, int total) {
    print("$sent $total");

Post binary data by Stream:

// Binary data
List postData = [...];
  data: Stream.fromIterable( => [e])), //create a Stream>
  options: Options(
    headers: {
      Headers.contentLengthHeader: postData.length, // set content-length

…you can find all examples code here.

Dio APIs

Creating an instance and set default configs.

You can create instance of Dio with an optional

Dio dio = new Dio(); // with default Options

// Set default configs dio.options.baseUrl = ""; dio.options.connectTimeout = 5000; //5s dio.options.receiveTimeout = 3000;

// or new Dio with a BaseOptions instance. BaseOptions options = new BaseOptions( baseUrl: "", 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(
    data: {"id":12,"name":"xx"},
    options: Options(method:"GET"),

Request method aliases

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(...)

Request Options

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: "". String baseUrl;

/// Http request headers. Map 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 extra;

/// Common query parameters Map*/ > queryParameters;


There is a complete example here.

Response Schema

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 redirects ;
  /// Returns the final real request uri (maybe redirect). 
  Uri realUri;    
  /// Custom field that you can retrieve it later in `then`.
  Map extra;

When request is succeed, you will receive the response as follows:

Response response = await dio.get("");


For each dio instance, We can add one or more interceptors, by which we can intercept requests or responses before they are handled by

    onRequest:(RequestOptions options) async {
     // Do something before request is sent
     return options; //continue
     // If you want to resolve the request with some custom data,
     // you can return a `Response` object or return `dio.resolve(data)`.
     // If you want to reject the request with a error message,
     // you can return a `DioError` object or return `dio.reject(errMsg)`
    onResponse:(Response response) async {
     // Do something with response data
     return response; // continue
    onError: (DioError e) async {
     // Do something with response error
     return  e;//continue

Simple interceptor example:

import 'package:dio/dio.dart';
class CustomInterceptors extends InterceptorsWrapper {
  Future onRequest(RequestOptions options) {
    print("REQUEST[${options?.method}] => PATH: ${options?.path}");
    return super.onRequest(options);
  Future onResponse(Response response) {
    print("RESPONSE[${response?.statusCode}] => PATH: ${response?.request?.path}");
    return super.onResponse(response);
  Future onError(DioError err) {
    print("ERROR[${err?.response?.statusCode}] => PATH: ${err?.request?.path}");
    return super.onError(err);

Resolve and reject the request

In all interceptors, you can interfere with their execution flow. If you want to resolve the request/response with some custom data,you can return a

object or return
. If you want to reject the request/response with a error message, you can return a
object or return
  onRequest:(RequestOptions options) {
   return dio.resolve("fake data")
Response response = await dio.get("/test");
print(;//"fake data"

Lock/unlock the interceptors

You can lock/unlock the interceptors by calling their

method. Once the request/response interceptor is locked, the incoming request/response will be added to a queue before they enter the interceptor, they will not be continued until the interceptor is unlocked.
tokenDio = new Dio(); //Create a new instance to request the token.
tokenDio.options = dio;
    onRequest:(Options options) async {
        // If no token, request token firstly and lock this interceptor
        // to prevent other request enter this interceptor.
        // We use a new Dio(to avoid dead lock) instance to request token.
        Response response = await tokenDio.get("/token");
        //Set the token to headers
        options.headers["token"] =["data"]["token"];
        return options; //continue

You can clean the waiting queue by calling



When the request interceptor is locked, the incoming request will pause, this is equivalent to we locked the current dio instance, Therefore, Dio provied the two aliases for the

of request interceptors.

dio.lock() == dio.interceptors.requestLock.lock()

dio.unlock() == dio.interceptors.requestLock.unlock()

dio.clear() == dio.interceptors.requestLock.clear()


Because of security reasons, we need all the requests to set up a csrfToken in the header, if csrfToken does not exist, we need to request a csrfToken first, and then perform the network request, because the request csrfToken progress is asynchronous, so we need to execute this async request in request interceptor. The code is as follows:

    onRequest: (Options options) async {
        print('send request:path:${options.path},baseURL:${options.baseUrl}');
        if (csrfToken == null) {
            print("no token,request token firstly...");
            //lock the dio.
            return tokenDio.get("/token").then((d) {
                options.headers["csrfToken"] = csrfToken =['data']['token'];
                print("request token succeed, value: " +['data']['token']);
                    'continue to perform request:path:${options.path},baseURL:${options.path}');
                return options;
            }).whenComplete(() => dio.unlock()); // unlock the dio
        } else {
            options.headers["csrfToken"] = csrfToken;
            return options;

For complete codes click here.


You can set

to print request/response log automaticlly, for example:
dio.interceptors.add(LogInterceptor(responseBody: false)); //开启请求日志

Custom Interceptor

You can custom interceptor by extending the

class. There is an example that implementing a simple cache policy: custom cache interceptor.

Cookie Manager

diocookiemanager package is a cookie manager for Dio.

Handling Errors

When a error occurs, Dio will wrap the

to a
try {
    await dio.get("");
} on DioError catch(e) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx and is also not 304.
    if(e.response) {
    } else{
        // Something happened in setting up or sending the request that triggered an Error

DioError scheme

  /// Response info, it may be `null` if the request can't reach to
  /// the http server, for example, occurring a dns error, network is not available.
  Response response;

/// Error descriptions. String message;

DioErrorType type;

/// The original error/exception object; It's usually not null when type /// is DioErrorType.DEFAULT dynamic error; }


enum DioErrorType {
  /// When opening  url timeout, it occurs.

///It occurs when receiving timeout. RECEIVE_TIMEOUT,

/// When the server response, but with a incorrect status, such as 404, 503... RESPONSE,

/// When the request is cancelled, dio will throw a error with this type. CANCEL,

/// Default error type, Some other Error. In this case, you can /// read the DioError.error if it is not null. DEFAULT, }

Using application/x-www-form-urlencoded format

By default, Dio serializes request data(except String type) to

. To send data in the
format instead, you can :
//Instance level
dio.options.contentType= Headers.formUrlEncodedContentType;
//or works once"/info", data:{"id":5}, 
         options: Options(contentType:Headers.formUrlEncodedContentType ));

Sending FormData

You can also send FormData with Dio, which will send data in the

, and it supports uploading files.
FormData formData = FormData.fromMap({
    "name": "wendux",
    "age": 25,
    "file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt")
response = await"/info", data: formData);

There is a complete example here.

Multiple files upload

There are two ways to add multiple files to

, the only difference is that upload keys are different for array types。
    "files": [
          filename: "upload.txt"),
          filename: "upload.txt"),

The upload key eventually becomes "files[]",This is because many back-end services add a middle bracket to key when they get an array of files. If you don't want “[]”,you should create FormData as follows(Don't use

  var formData = FormData();
          filename: "upload.txt"),
          filename: "upload.txt"),


allows changes to the request/response data before it is sent/received to/from the server. This is only applicable for request methods 'PUT', 'POST', and 'PATCH'. Dio has already implemented a
, and as the default
. If you want to customize the transformation of request/response data, you can provide a
by your self, and replace the
by setting the

In flutter

If you use dio in flutter development, you'd better to decode json in background with [compute] function.

// Must be top-level function
_parseAndDecode(String response) {
  return jsonDecode(response);

parseJson(String text) { return compute(_parseAndDecode, text); }

void main() { ... //Custom jsonDecodeCallback (dio.transformer as DefaultTransformer).jsonDecodeCallback = parseJson; runApp(MyApp()); }

Other Example

There is an example for customizing Transformer.


HttpClientAdapter is a bridge between Dio and HttpClient.

Dio implements standard and friendly API for developer.

HttpClient: It is the real object that makes Http requests.

We can use any HttpClient not just

to make the Http request. And all we need is providing a
. The default HttpClientAdapter for Dio is
dio.httpClientAdapter = new DefaultHttpClientAdapter();

Here is a simple example to custom adapter.

Using proxy

provide a callback to set proxy to
, for example:
import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
    // config the http client
    client.findProxy = (uri) {
        //proxy all request to localhost:8888
        return "PROXY localhost:8888";
    // you can also create a new HttpClient to dio
    // return new HttpClient();

There is a complete example here.

Https certificate verification

There are two ways to verify the https certificate. Suppose the certificate format is PEM, the code like:

String PEM="XXXXX"; // certificate content
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
    client.badCertificateCallback=(X509Certificate cert, String host, int port){
        if(cert.pem==PEM){ // Verify the certificate
            return true;
        return false;

Another way is creating a

when create the
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
    SecurityContext sc = new SecurityContext();
    //file is the path of certificate
    HttpClient httpClient = new HttpClient(context: sc);
    return httpClient;

In this way, the format of certificate must be PEM or PKCS12.

Http2 support

diohttp2adapter package is a Dio HttpClientAdapter which support Http/2.0 .


You can cancel a request using a cancel token. One token can be shared with multiple requests. When a token's

method invoked, all requests with this token will be cancelled.
CancelToken token = CancelToken();
dio.get(url1, cancelToken: token);
dio.get(url2, cancelToken: token);

// cancel the requests with "cancelled" message. token.cancel("cancelled");

There is a complete example here.

Extends Dio class

is a abstract class with factory constructor,so we don't extend
class directy. For this purpose, we can extend
instead, for example:
import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart'; //If in browser, import 'package:dio/browser_imp.dart'

class Http extends DioForNative { Http([BaseOptions options]):super(options){ // do something } }

We can also implement our Dio client:

class MyDio with DioMixin implements Dio{
  // ...

Copyright & License

This open source project authorized by , and the license is MIT.

Features and bugs

Please file feature requests and bugs at the issue tracker.


Buy a cup of coffee for me (Scan by wechat):

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.