free geoip
20

Using Dio for API Requests in Dart

In Dart and Flutter development, handling HTTP requests efficiently is essential, and one of the best tools for the job…

In Dart and Flutter development, handling HTTP requests efficiently is essential, and one of the best tools for the job is the Dio package. Dio offers powerful features such as request cancellation, timeout, interceptors, form data handling, and file downloading—making it a superior choice over Dart’s default http package.

Using Dio for API Requests in Dart

Why Use Dio in Dart?

Dio is a powerful HTTP client for Dart, ideal for RESTful API interaction. With its intuitive API and support for modern request features, Dio simplifies many common networking tasks, including:

  • Setting global headers and interceptors
  • Handling exceptions with ease
  • Customizing timeout and retry logic
  • Uploading files with progress reporting

You can learn more about Dio’s capabilities and updates from the official Dio documentation.

Step-by-Step Guide: API Request Using Dio

Step 1: Add Dio Dependency

Add the following to your pubspec.yaml file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dependencies:
dio: ^5.4.0
dependencies: dio: ^5.4.0
dependencies:
  dio: ^5.4.0

Then run flutter pub get.

Step 2: Create API Client Class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// api_client.dart
import 'package:dio/dio.dart';
class ApiClient {
final Dio _dio = Dio(
BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
connectTimeout: Duration(seconds: 10),
receiveTimeout: Duration(seconds: 10),
headers: {
'Content-Type': 'application/json',
},
),
);
Future<List<dynamic>> getPosts() async {
try {
final response = await _dio.get('/posts');
return response.data;
} on DioException catch (e) {
throw Exception('Failed to load posts: ${e.message}');
}
}
}
// api_client.dart import 'package:dio/dio.dart'; class ApiClient { final Dio _dio = Dio( BaseOptions( baseUrl: 'https://jsonplaceholder.typicode.com', connectTimeout: Duration(seconds: 10), receiveTimeout: Duration(seconds: 10), headers: { 'Content-Type': 'application/json', }, ), ); Future<List<dynamic>> getPosts() async { try { final response = await _dio.get('/posts'); return response.data; } on DioException catch (e) { throw Exception('Failed to load posts: ${e.message}'); } } }
// api_client.dart
import 'package:dio/dio.dart';

class ApiClient {
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'https://jsonplaceholder.typicode.com',
      connectTimeout: Duration(seconds: 10),
      receiveTimeout: Duration(seconds: 10),
      headers: {
        'Content-Type': 'application/json',
      },
    ),
  );

  Future<List<dynamic>> getPosts() async {
    try {
      final response = await _dio.get('/posts');
      return response.data;
    } on DioException catch (e) {
      throw Exception('Failed to load posts: ${e.message}');
    }
  }
}

Step 3: Call API from UI

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// main.dart
import 'package:flutter/material.dart';
import 'api_client.dart';
void main() => runApp(MyApp());
class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> {
final ApiClient apiClient = ApiClient();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dio API Example',
home: Scaffold(
appBar: AppBar(title: Text('Dio API Example')),
body: FutureBuilder<List<dynamic>>(
future: apiClient.getPosts(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final posts = snapshot.data!;
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(posts[index]['title']),
subtitle: Text(posts[index]['body']),
);
},
);
},
),
),
);
}
}
// main.dart import 'package:flutter/material.dart'; import 'api_client.dart'; void main() => runApp(MyApp()); class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> { final ApiClient apiClient = ApiClient(); @override Widget build(BuildContext context) { return MaterialApp( title: 'Dio API Example', home: Scaffold( appBar: AppBar(title: Text('Dio API Example')), body: FutureBuilder<List<dynamic>>( future: apiClient.getPosts(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}')); } final posts = snapshot.data!; return ListView.builder( itemCount: posts.length, itemBuilder: (context, index) { return ListTile( title: Text(posts[index]['title']), subtitle: Text(posts[index]['body']), ); }, ); }, ), ), ); } }
// main.dart
import 'package:flutter/material.dart';
import 'api_client.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final ApiClient apiClient = ApiClient();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dio API Example',
      home: Scaffold(
        appBar: AppBar(title: Text('Dio API Example')),
        body: FutureBuilder<List<dynamic>>(
          future: apiClient.getPosts(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            }

            final posts = snapshot.data!;
            return ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(posts[index]['title']),
                  subtitle: Text(posts[index]['body']),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

Summary

Dio is a feature-rich package that makes handling HTTP requests in Dart and Flutter significantly easier and more manageable. Whether you’re working with simple REST APIs or complex request flows, Dio provides a cleaner, more customizable solution.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *