Dio helps your app talk to the internet easily and powerfully. It manages requests and responses with extra features.
Dio package for advanced HTTP in Flutter
final dio = Dio(); // Making a GET request final response = await dio.get('https://example.com/api/data', queryParameters: {'key': 'value'}, options: Options(headers: {'Authorization': 'Bearer token'}), ); // Handling response print(response.data);
Use Dio() to create a client for HTTP calls.
Use get, post, put, etc. methods for requests.
final dio = Dio(); final response = await dio.get('https://jsonplaceholder.typicode.com/posts'); print(response.data);
final dio = Dio(); final response = await dio.post('https://example.com/login', data: {'username': 'user', 'password': 'pass'}); print(response.data);
final dio = Dio(); dio.interceptors.add(InterceptorsWrapper( onRequest: (options, handler) { print('Request to: ' + options.uri.toString()); return handler.next(options); }, onResponse: (response, handler) { print('Response status: ' + response.statusCode.toString()); return handler.next(response); }, onError: (DioError e, handler) { print('Error: ' + e.message); return handler.next(e); }, ));
This app uses Dio to fetch a list of posts from a public API. It shows a loading spinner while waiting, then displays the posts in a scrollable list. If loading fails, it shows an error message.
import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Dio HTTP Example')), body: Center(child: PostsList()), ), ); } } class PostsList extends StatefulWidget { @override _PostsListState createState() => _PostsListState(); } class _PostsListState extends State<PostsList> { final Dio dio = Dio(); List<dynamic> posts = []; bool loading = true; String error = ''; @override void initState() { super.initState(); fetchPosts(); } Future<void> fetchPosts() async { try { final response = await dio.get('https://jsonplaceholder.typicode.com/posts'); setState(() { posts = response.data; loading = false; }); } catch (e) { setState(() { error = 'Failed to load posts'; loading = false; }); } } @override Widget build(BuildContext context) { if (loading) { return CircularProgressIndicator(); } if (error.isNotEmpty) { return Text(error); } return ListView.builder( itemCount: posts.length, itemBuilder: (context, index) { final post = posts[index]; return ListTile( title: Text(post['title']), subtitle: Text(post['body']), ); }, ); } }
Dio supports request cancellation using CancelToken.
You can add interceptors to modify requests or handle errors globally.
Use Options to customize headers, timeouts, and response types.
Dio is a powerful HTTP client for Flutter with many features.
It simplifies making requests, handling errors, and customizing calls.
Use interceptors and options to control request and response behavior.
Practice
Solution
Step 1: Understand Dio's role
Dio is designed as an HTTP client to simplify network calls in Flutter apps.Step 2: Compare with other options
Other options like UI animations or database management are unrelated to Dio's purpose.Final Answer:
To make HTTP requests easily with advanced features -> Option CQuick Check:
Dio = HTTP client [OK]
- Confusing Dio with UI or database packages
- Thinking Dio handles gestures
- Assuming Dio is for local storage
Solution
Step 1: Check Dio instance creation syntax
Dio requires BaseOptions to set baseUrl during initialization.Step 2: Validate each option
var dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); uses BaseOptions correctly; others misuse constructor or methods.Final Answer:
var dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); -> Option AQuick Check:
BaseOptions sets baseUrl in Dio [OK]
- Passing URL directly to Dio constructor
- Using nonexistent setBaseUrl method
- Setting baseUrl as a direct parameter
var dio = Dio();
var response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');
print(response.data['id']);What will be printed?
Solution
Step 1: Understand the GET request
The code fetches post with id 1 from the API.Step 2: Access response data
response.data['id'] accesses the 'id' field, which is 1.Final Answer:
1 -> Option AQuick Check:
response.data['id'] = 1 [OK]
- Expecting entire JSON instead of specific field
- Not awaiting the async call
- Using wrong key to access data
var dio = Dio();
var response = dio.get('https://api.example.com/data');
print(response.data);Solution
Step 1: Check async call usage
dio.get returns a Future; it must be awaited to get response.Step 2: Identify missing await
Code lacks await, so response is a Future, not the actual response object.Final Answer:
Missing await keyword for async call -> Option DQuick Check:
Async calls need await [OK]
- Forgetting await on async requests
- Assuming dio.get is synchronous
- Trying to access data on Future object
Solution
Step 1: Understand global headers setup
Headers for all requests are set in BaseOptions.headers when creating Dio.Step 2: Evaluate options
Setting headers in BaseOptions applies them globally to all requests; adding them per get/post call is request-specific; there is no addHeader method on Dio; response interceptors handle responses, not request headers.Final Answer:
Set headers in BaseOptions when creating Dio instance -> Option BQuick Check:
Global headers = BaseOptions.headers [OK]
- Trying to add headers via nonexistent methods
- Setting headers only per request instead of globally
- Confusing response interceptors with request headers
Ready to prove it?
Pass the test and this pattern moves unknown
