CodeBlanks Logo Icon CodeBlanks

dio

Learn the advanced HTTP client with dio.

The dio package

dio is a more powerful HTTP client than the http package. It offers interceptors, timeouts, automatic JSON parsing, cancelable requests and FormData support.

Usage: create a client with var dio = Dio();. var r = await dio.get('https://api.example.com/users');. r.data is automatically parsed JSON (a Map or List).

dio is preferred over http in larger projects because of its interceptor chain and advanced configuration.

Configuration with BaseOptions

Dio(BaseOptions(baseUrl: 'https://api.example.com', connectTimeout: Duration(seconds: 5))) configures the client. baseUrl is prefixed to all requests.

So dio.get('/users') hits https://api.example.com/users. Timeouts are set separately for connection and reading.

Interceptors are added with dio.interceptors.add(...); used for logging, retry, auth token injection. This layered design gives power in large projects.

Practice Configure Dio with BaseOptions

Add import 'package:dio/dio.dart';. Inside main add var dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'));. Add print(dio.options.baseUrl);.

Starter code

main.dart
void main() {
  // add dio import; set baseUrl via BaseOptions; print baseUrl
}

Sample solution

main.dart
import 'package:dio/dio.dart';

void main() {
  var dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
  print(dio.options.baseUrl);
}

Expected output

https://api.example.com

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Dio client

Question
var dio = ____();
Answer
var dio = Dio();

Explanation: Dio() creates a new dio client.

2 Match the dio features

Term Meaning
BaseOptions Configuration
interceptors Request chain
data Auto JSON
cancelToken Request cancellation

3 What does dio do automatically?

  • Starts a new Isolate
  • Opens a database
  • Parses the JSON body Correct answer
  • Draws UI

Explanation: dio parses the JSON body automatically (r.data is a Map/List).

All lessons in Advanced