How to Use Dio Package in Flutter for HTTP Requests
To use the
dio package in Flutter, first add it to your pubspec.yaml file, then import it and create a Dio instance to make HTTP requests like GET or POST. You can customize requests with options, interceptors, and handle responses asynchronously using async/await.Syntax
The basic syntax to use dio involves creating a Dio object, then calling methods like get, post, etc. Each method returns a Response object asynchronously.
- Dio(): Creates a Dio client instance.
- get(url): Sends a GET request to the URL.
- post(url, data): Sends a POST request with data.
- Response: Contains the server response data.
dart
import 'package:dio/dio.dart'; void main() async { final dio = Dio(); final response = await dio.get('https://example.com'); print(response.data); }
Output
Prints the response body from https://example.com
Example
This example shows how to make a GET request to fetch JSON data from a public API and print the title from the response.
dart
import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final Dio dio = Dio(); Future<String> fetchTitle() async { final response = await dio.get('https://jsonplaceholder.typicode.com/todos/1'); return response.data['title']; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Dio Example')), body: Center( child: FutureBuilder<String>( future: fetchTitle(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text('Title: ${snapshot.data}'); } }, ), ), ), ); } }
Output
App shows a centered text: Title: delectus aut autem
Common Pitfalls
Common mistakes when using dio include:
- Not adding
awaitbefore async calls, causing unexpected behavior. - Ignoring exceptions; always use
try-catchto handle errors. - Forgetting to add
diotopubspec.yamldependencies. - Not setting correct headers or options for requests needing authentication.
dart
import 'package:dio/dio.dart'; void wrongUsage() async { final dio = Dio(); // Missing await - this will not wait for response final response = dio.get('https://example.com'); print(response); // Prints Future<Response>, not actual data } void correctUsage() async { final dio = Dio(); try { final response = await dio.get('https://example.com'); print(response.data); } catch (e) { print('Error: $e'); } }
Output
wrongUsage prints Instance of 'Future<Response>'
correctUsage prints actual response data or error message
Quick Reference
Here is a quick reference for common Dio methods and options:
| Method/Option | Description |
|---|---|
| Dio() | Create Dio client instance |
| get(url) | Send GET request |
| post(url, data) | Send POST request with data |
| put(url, data) | Send PUT request |
| delete(url) | Send DELETE request |
| options.headers | Set HTTP headers |
| options.connectTimeout | Set connection timeout in ms |
| interceptors | Add interceptors for request/response |
| cancelToken | Cancel ongoing requests |
Key Takeaways
Add dio package to pubspec.yaml and import it to use in Flutter.
Create a Dio instance and use async/await to make HTTP requests.
Always handle errors with try-catch to avoid app crashes.
Use Dio options and interceptors to customize requests.
Remember to await async calls to get actual response data.