Dart – 30 – Network Requests

Network Requests in Dart

Network requests are a fundamental aspect of modern application development, enabling communication with remote servers and the exchange of data. Dart, as a versatile programming language, offers powerful libraries for making network requests, whether you’re building web applications, command-line tools, or mobile apps. In this discussion, we’ll explore how to perform network requests in Dart, covering concepts such as HTTP client libraries, making GET and POST requests, handling responses, and error handling.

HTTP Client Libraries

Dart provides built-in HTTP client libraries that simplify the process of making network requests. Two commonly used libraries are http and dio. The http library offers a straightforward way to perform HTTP requests, while dio provides additional features like request cancellation and interceptors.

Here’s how to import the http library:


import 'package:http/http.dart' as http;
    
Making GET Requests

GET requests are used to retrieve data from a server. In Dart, you can use the http.get method to perform a GET request and fetch data from a specified URL.

Here’s how to make a GET request using the http library:


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

void fetchData() async {
    final response = await http.get(Uri.parse('https://api.example.com/data'));
    if (response.statusCode == 200) {
        print('Data: ${response.body}');
    } else {
        print('Request failed with status: ${response.statusCode}');
    }
}
    
Making POST Requests

POST requests are used to send data to a server, often to update or create resources. In Dart, you can use the http.post method to perform a POST request with data in the request body.

Here’s how to make a POST request using the http library:


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

void sendData() async {
    final response = await http.post(
        Uri.parse('https://api.example.com/data'),
        body: {'key': 'value'},
    );

    if (response.statusCode == 201) {
        print('Resource created successfully.');
    } else {
        print('Request failed with status: ${response.statusCode}');
    }
}
    
Handling Responses

When you make a network request, you receive a response from the server. You should handle this response to extract data and handle any errors. Dart’s HTTP client libraries return response objects that provide access to the response status code, headers, and body.

Here’s how to extract data from a response using the http library:


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

void fetchData() async {
    final response = await http.get(Uri.parse('https://api.example.com/data'));

    if (response.statusCode == 200) {
        final data = response.body;
        // Process and use the data
    } else {
        print('Request failed with status: ${response.statusCode}');
    }
}
    
Error Handling

When making network requests, it’s crucial to handle potential errors gracefully. Network requests can fail for various reasons, such as a loss of internet connection or server issues. Dart allows you to catch and handle exceptions when working with network requests.

Here’s an example of error handling when making a network request:


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

void fetchData() async {
    try {
        final response = await http.get(Uri.parse('https://api.example.com/data'));

        if (response.statusCode == 200) {
            final data = response.body;
            // Process and use the data
        } else {
            print('Request failed with status: ${response.statusCode}');
        }
    } catch (e) {
        print('Error: $e');
    }
}
    
Conclusion

Network requests play a central role in many Dart applications, allowing data exchange with remote servers. By leveraging Dart’s HTTP client libraries, making GET and POST requests, handling responses, and implementing error handling, you can create robust applications that interact effectively with external resources. Understanding these concepts is vital for building web applications, mobile apps, and more in Dart.