πŸ—ΌNetworking

In Flutter, the http package is commonly used for sending HTTP requests to a server. Let’s explore how you can perform GET and POST requests.

1. Adding the http Package πŸ“¦

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

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0

Run flutter pub get to install the new dependency.

2. Sending a GET Request πŸ“€

Here’s how you can send a GET request to fetch data from a server:

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

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

  if (response.statusCode == 200) {
    // If the server returns an OK response, parse the JSON
    print('Response data: ${response.body}');
  } else {
    // If the server did not return a 200 OK response, throw an exception.
    throw Exception('Failed to load post');
  }
}

3. Sending a POST Request πŸ“₯

Here’s how you can send a POST request to create new data on a server:

4. Error Handling πŸ›‘

It's important to handle any errors that occur when sending requests:

Complete Example Code πŸ“œ

Let's put everything together in a complete Flutter app:

In this complete example:

  • We first add the http dependency in pubspec.yaml.

  • We define a NetworkingExample stateful widget.

  • In the _NetworkingExampleState class, we define a fetchData method that sends a GET request to fetch data.

  • We use a FloatingActionButton to trigger the fetchData method.

  • We display the fetched data or any error messages to the user.


Assignments πŸ“

Here are some exercises to reinforce your understanding:

Last updated

Was this helpful?