Tillitsdone
down Scroll to discover

Advanced Dio Configuration in Flutter Guide

Master Dio configuration in Flutter for custom headers and timeouts.

Learn how to implement dynamic headers, handle authentication tokens, and create flexible timeout strategies for robust API calls.
thumbnail

Advanced Configuration of Dio in Flutter for Custom Headers and Timeouts

Crystalline formations in amber and cream colors intricate lattice patterns resembling network connections shot from 45-degree angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

In the world of Flutter development, making HTTP requests is a daily task we can’t avoid. While there are several HTTP clients available, Dio stands out as a powerful and flexible option. Today, let’s dive deep into configuring Dio for custom headers and timeouts - essential aspects for building robust applications.

Setting Up Base Configuration

When working with Dio, it’s crucial to start with a well-structured base configuration. This foundation will make our API calls more maintainable and consistent across the application.

Abstract fluid patterns in rich blue and orange tones flowing like data streams through space captured from bird's eye view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

final dio = Dio(BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 3),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
));

Implementing Custom Headers

Headers play a crucial role in API communication. Let’s explore how to handle different scenarios, from authentication tokens to device-specific information.

class ApiService {
final Dio _dio;
ApiService() {
_dio = Dio();
_setupInterceptors();
}
void _setupInterceptors() {
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// Add dynamic headers
options.headers['Authorization'] = 'Bearer ${getToken()}';
options.headers['Device-ID'] = getDeviceId();
return handler.next(options);
},
));
}
}

Aerial view of green and yellow terrain patterns forming abstract geometric shapes photographed straight down from above high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Advanced Timeout Strategies

Different API endpoints might require different timeout configurations. Here’s how to implement flexible timeout strategies:

Future<Response> makeRequest({
required String endpoint,
Duration? customTimeout,
bool isLongOperation = false,
}) async {
try {
return await _dio.get(
endpoint,
options: Options(
sendTimeout: customTimeout ??
(isLongOperation ? const Duration(seconds: 30) : const Duration(seconds: 5)),
receiveTimeout: customTimeout ??
(isLongOperation ? const Duration(seconds: 30) : const Duration(seconds: 5)),
),
);
} on DioException catch (e) {
// Handle timeout exceptions gracefully
if (e.type == DioExceptionType.connectionTimeout ||
e.type == DioExceptionType.sendTimeout ||
e.type == DioExceptionType.receiveTimeout) {
throw TimeoutException('The request timed out');
}
rethrow;
}
}

By implementing these configurations, your Flutter application will be better equipped to handle various network scenarios, from poor connections to complex API requirements. Remember to always test these implementations thoroughly, especially under different network conditions.

Ocean waves creating natural patterns in bright green and mahogany colors viewed from side angle at 30 degrees high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svgicons/flutter.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.