๐Ÿ“ก Handling API Requests in Flutter with HTTP and Dio ๐Ÿš€

Manoj JaiswalManoj Jaiswal
4 min read

When building mobile applications, youโ€™ll often need to connect your app to a server to fetch or send data. In Flutter, handling API requests is made easy with libraries like HTTP and Dio. Both are powerful tools, but each has its own set of advantages depending on your needs.

In this article, we'll dive into how to handle API requests using these two popular packages.

๐ŸŒ Why You Need API Requests

In many mobile apps, communicating with a server to retrieve data or send updates is essential. For example:

  • Fetching a list of products for an e-commerce app ๐Ÿ›’.

  • Sending user information to a backend after login ๐Ÿ”‘.

  • Pulling real-time weather updates ๐ŸŒฆ๏ธ.

Flutter offers several tools to make working with APIs seamless. Let's explore two of the most common ones: HTTP and Dio.


1. ๐Ÿ› ๏ธ Using the HTTP Package

The http package is the simpler and more lightweight of the two. Itโ€™s great for quick and easy API calls without complex configurations.

๐Ÿ“ฆ Installing the HTTP Package

To start, add the http package to your pubspec.yaml file:

dependencies:
  http: ^0.14.0

Then, run:

flutter pub get

๐Ÿ“„ Making a GET Request

Here's how to make a simple GET request using http:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> fetchData() async {
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  final response = await http.get(url);

  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);
    print(data); // Process the data here
  } else {
    print('Failed to load data');
  }
}

๐Ÿง  Explanation:

  • We use http.get() to make a GET request to an API.

  • The response.statusCode == 200 check ensures the request was successful.

  • jsonDecode() converts the JSON response to a Dart object.

โฉ Making a POST Request

Sending data to the server is also straightforward:

Future<void> sendData() async {
  final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  final response = await http.post(
    url,
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({'title': 'Flutter', 'body': 'Building apps', 'userId': 1}),
  );

  if (response.statusCode == 201) {
    print('Data sent successfully!');
  } else {
    print('Failed to send data');
  }
}

Pros of HTTP:

  • Simple and lightweight ๐Ÿชถ.

  • Easy to use for basic requests like GET and POST.

Cons of HTTP:

  • Limited features: lacks advanced functionality like interceptors, retries, or download/upload progress ๐Ÿ“‰.

2. โšก Using the Dio Package

If you need more advanced features, Dio is your go-to package. It supports:

  • Interceptors for modifying requests/responses ๐Ÿ›‘.

  • Retry mechanisms ๐Ÿ”.

  • Progress tracking for file uploads/downloads โฌ‡๏ธ.

๐Ÿ“ฆ Installing Dio

Add dio to your pubspec.yaml:

dependencies:
  dio: ^5.0.0

Run the following command:

flutter pub get

โš™๏ธ Making a GET Request with Dio

Hereโ€™s how you can use Dio for a GET request:

import 'package:dio/dio.dart';

Future<void> fetchDataWithDio() async {
  Dio dio = Dio();
  final response = await dio.get('https://jsonplaceholder.typicode.com/posts');

  if (response.statusCode == 200) {
    print(response.data); // Process the data here
  } else {
    print('Error: ${response.statusCode}');
  }
}

๐Ÿ”„ Making a POST Request with Dio

Hereโ€™s how to send data to a server using Dio:

Future<void> sendDataWithDio() async {
  Dio dio = Dio();
  final response = await dio.post(
    'https://jsonplaceholder.typicode.com/posts',
    data: {'title': 'Dio', 'body': 'Advanced features', 'userId': 1},
  );

  if (response.statusCode == 201) {
    print('Data sent successfully!');
  } else {
    print('Error: ${response.statusCode}');
  }
}

๐Ÿš€ Handling Errors and Timeouts

Dio makes it easier to handle errors and timeouts. Hereโ€™s an example:

try {
  final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
} on DioError catch (e) {
  if (e.type == DioErrorType.connectTimeout) {
    print('Connection timeout');
  } else if (e.type == DioErrorType.response) {
    print('Error: ${e.response?.statusCode}');
  }
}

๐Ÿ† Advanced Features of Dio:

  • Interceptors: Modify requests and responses on the fly.

  • Timeouts: Customizable connection and response timeouts โฑ๏ธ.

  • Download/Upload Progress: Track the progress of file uploads or downloads ๐Ÿ“‚.

Pros of Dio:

  • Full-featured, supports advanced use cases ๐Ÿ‹๏ธโ€โ™‚๏ธ.

  • Easier error handling, request/response manipulation.

Cons of Dio:

  • Slightly heavier and more complex to set up compared to http.

โš”๏ธ HTTP vs. Dio: Which One to Use?

  • Go with HTTP if youโ€™re building a simple app with basic API interactions. Itโ€™s lightweight and gets the job done for simple use cases.

  • Choose Dio if you need more control over requests, error handling, or plan to handle large files (like images or PDFs). Itโ€™s feature-rich and perfect for advanced scenarios.


๐Ÿ Conclusion

Handling API requests in Flutter is straightforward with both HTTP and Dio. While HTTP is perfect for lightweight apps and simpler tasks, Dio offers powerful features that make it ideal for more complex applications. Choose the one that fits your project's needs and start building powerful, connected apps! ๐ŸŒ๐Ÿ’ป

Happy coding! ๐ŸŽ‰

#flutterindore #flutter developer #bestflutterdevloper

0
Subscribe to my newsletter

Read articles from Manoj Jaiswal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Jaiswal
Manoj Jaiswal

I am a Software Engineer with 3+ years of experience designing and developing mobile and web applications using flutter and python django. I specialization in flutter and have professional experience working with dart language. Also i have experience working with python django and node js.