Networking in Flutter Using the HTTP Package

Learn via video courses
Topics Covered

Overview

The http package in Flutter is a popular choice for handling network requests and integrating with APIs of any kind. It enables developers to make HTTP requests, parse JSON data, upload, download files, and handle errors. By using the http package, Flutter developers can seamlessly communicate with backend servers and fetch data for their applications. This package allows developers to perform various types of requests and hit endpoints, such as GET, POST, PUT, and DELETE, and efficiently handle responses and errors.

Installing and Configuring the HTTP Package

Step - 1:

Update the dependencies in your pubspec.yaml file Open your Flutter project and locate the pubspec.yaml file. This file is located at the root of your Flutter project directory. In the pubspec.yaml file, you need to update the dependencies section to include the http package.

The ^1.1.0 version constraint indicates that you want to use a version of the http flutter package that is at least 1.1.0 but less than the next major version.

Step - 2: Fetch the Package

After updating the pubspec.yaml file, save the changes. Open your terminal or command prompt, navigate to the root of your Flutter project, and run the following command to fetch and download the http flutter package to your project:

This command will download the http flutter package and its dependencies into your project's pubspec.lock file.

Step - 3: Import the HTTP Package

To use the http flutter package in your Dart files, you need to import it at the top of the file. Add the following import statement in the required files of the project:

The as http part is optional but recommended as it provides a convenient way to prefix the http flutter package classes and avoid naming conflicts with other classes in your project.

Making Requests with the HTTP Package

With the http Flutter package installed and imported, you can now make HTTP requests in your Flutter application. The http flutter package provides various methods for different types of requests, such as including GET, POST, PUT, and DELETE. These methods return Future objects that represent the asynchronous nature of the network requests.

Sending a GET Request

To send a GET request using the http flutter package, you can use the http.get() method. This method takes a Uri object representing the URL of the API endpoint you want to fetch data from. It returns a Future<http.Response> object.

Sending a POST Request

To send a POST request using the http flutter package, you can use the http.post() method. This method takes a Uri object representing the URL of the API endpoint and an optional body parameter containing the data you want to send with the request.

Sending PUT and DELETE Request

For sending PUT and DELETE requests, The http.put() and http.delete() methods work in the same way as the GET and POST methods, but with the appropriate HTTP method.

Customizing Requests

The http flutter package allows you to customize your requests by adding headers, query parameters, and timeout configurations.

This flexibility enables you to communicate effectively with APIs that require specific headers or filtering options.

To add headers to your requests, you can pass a Map<String, String> to the headers parameter of the request methods. Each key-value pair represents a header field and its value.

Parsing JSON Data with the HTTP Package

When a GET request is made or an API endpoint is hit, often the response from the API is in JSON format/data.

The http flutter package provides built-in support for parsing JSON data using the jsonDecode() function from the dart:convert library.

Fetching JSON Data

To fetch JSON data from an API using the http flutter package. We can use the http.get() method to send a GET request and receive a JSON response.

If the response's status code is 200 (indicating a successful request), we decode the response's body using jsonDecode() and store it in the jsonData variable. You can then process the parsed JSON data as per your application's requirements.

Accessing JSON Data

Once the JSON data is parsed, we can access its values by using the appropriate keys or indices. The jsonData object, is typically a Map<String, dynamic>, depending on the structure of the JSON data.

Working with Nested JSON Data

More often than not, JSON responses contain nested structures that require accessing values within nested objects or arrays. To access nested values, you can chain the key access operations.

Model Classes and Serialization

As your application grows, it becomes beneficial to map JSON data to Dart objects using model classes. Model classes help organize and work with JSON data more effectively.

Additionally, you can use serialization libraries like json_serializable or built_value to automate the conversion between JSON and Dart objects.

Uploading and Downloading Files with the HTTP Package

In addition to making regular API requests, the http package in Flutter also provides support for uploading and downloading files. This functionality enables you to work with applications that involve file sharing, media uploads, or any form of file transfer.

Uploading Files

To upload a file to a server using the http flutter package, we need to create a multipart request. A multipart request allows us to send both file data and additional form data in a single request.

Downloading Files

To download a file using the http flutter package, we can use the http.get() method and save the response to a file on the device.

File Upload and Download Progress

In some cases, you may need to track the progress of file uploads or downloads. The http flutter package allows you to monitor the progress of these operations using the http.StreamedRequest and http.ByteStream classes.

Handling Errors with the HTTP Package

Network requests can fail due to various reasons, such as network connectivity issues, server errors, or incorrect API endpoints. Here's how you can handle errors while using a http package:

Handling Network Errors

Network errors can occur when the device has no internet connection or when there are issues with network connectivity. To handle network errors, you can use try-catch blocks and check for specific exceptions.

Handling Server Errors

Server errors can occur when the server returns an error status code, indicating an issue with the request or the server-side processing. It is essential to handle server errors and provide meaningful feedback to the user.

Handling JSON Parsing Errors

When parsing JSON data received from an API response, errors can occur if the JSON structure is invalid or does not match the expected format. To handle JSON parsing errors, you can use try-catch blocks and handle the exception accordingly.

Displaying Error Messages

When an error occurs during network requests, it is essential to provide meaningful error messages to the user. You can display error messages using Flutter's built-in error handling mechanisms, such as SnackBars or AlertDialogs.

Best Practices of Using the HTTP Package

  • Use a Single Instance of http.Client:
    It is recommended to create a single instance of the http.Client class and reuse it for multiple requests. Creating multiple instances can lead to resource leaks and inefficient memory usage.
  • Set Appropriate Request Headers:
    Setting the appropriate request headers such as Content-Type, Authorization, and User-Agent. Ensure that you set the headers correctly based on the API requirements and authentication mechanisms.
  • Implement Connection Timeouts:
    To prevent your application from hanging indefinitely due to network issues, it's important to set connection timeouts for your requests. The http package allows you to specify the maximum duration to wait to establish a connection using the timeout parameter.
  • Handle Response Timeouts:
    You can implement a timer or use libraries like dio that provide built-in timeout handling mechanisms. Be mindful of the response times of the APIs you are interacting with and set appropriate timeouts accordingly.
  • Implement Retry Logic:
    Network requests can sometimes fail due to temporary issues. Implementing retry logic can help in handling such scenarios. You can retry failed requests with exponential backoff or implement a custom retry mechanism based on the specific needs of your application.
  • Implement Error Handling and Logging:
    Catch exceptions, handle network errors, and provide meaningful error messages to the user. Additionally, consider logging error messages and request/response details for debugging purposes.
  • Use SSL/TLS:
    When communicating with secure APIs over HTTPS, ensure that you are using SSL/TLS to establish a secure connection. The http package supports secure connections by default. However, it's important to validate SSL certificates and handle certificate errors appropriately.
  • Implement Pagination and Batch Requests:
    If you are working with APIs that return large datasets, consider implementing pagination or batch requests to retrieve data in chunks. This can improve performance and reduce the load on both the client and server.
  • Test and Mock API Requests:
    Proper testing of network requests allows you to ensure the stability of your application. Write unit tests to validate the behavior of your API requests and consider using mock server responses for testing purposes.
  • Keep Security in Mind:
    When working with sensitive data or performing authenticated requests, follow security best practices. Avoid exposing sensitive information like API keys or tokens in your codebase. Consider using environment variables or secure storage solutions to store and access sensitive information.

Example App

To demonstrate the use of the http package and networking in Flutter, we will be building a demo app that will fetch movie data from an API called 'TMDB' which consists of all movies and data related to them.

The application makes a GET request to the API server or hits the endpoint to retrieve data of movies and returns the data to the app in JSON which is decoded by the json.decode function.

Ensure to add the http package to your pubspec.yaml file and fetch the package to your project directory.

Note:
Here, The API Key is hidden in a .env file for security reasons, please ensure to replace the 'api_key' part with your API key as per your use case.

You can find the source code of the app below:

main.dart file:

The output of the above demo app would look like this:

example application of using http package in flutter

You can also find the complete source code of the application here: link

Conclusion

  • The http package in Flutter allows us to make HTTP requests to any API and handle the responses effectively.
  • Making requests with the http package involves creating instances of the http.Client class and using methods like get, post, put, and delete to perform different types of requests.
  • Parsing JSON data with the http package enables us to extract and utilize the data returned by the API responses. The jsonDecode function helps in converting JSON strings into Dart objects.
  • Uploading and downloading files using the http package is made possible by utilizing multipart requests, which allow us to send and receive files along with other form data.
  • The http package allows us to handle network errors, server errors, and JSON parsing errors using try-catch blocks and appropriate error-handling mechanisms.