# 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:

```yaml
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:

```dart
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:

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

Future<void> createPost() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    body: {
      'title': 'foo',
      'body': 'bar',
      'userId': '1',
    },
  );

  if (response.statusCode == 201) {
    // If the server returns a CREATED response, parse the JSON
    print('Created post: ${response.body}');
  } else {
    // If the server did not return a 201 CREATED response, throw an exception.
    throw Exception('Failed to create post');
  }
}
```

## 4. Error Handling 🛑

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

```dart
try {
  await fetchPost();
} catch (error) {
  print('Failed to load post: $error');
}
```

## Complete Example Code 📜

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

{% tabs %}
{% tab title="Code" %}

```dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NetworkingExample(),
    );
  }
}

class NetworkingExample extends StatefulWidget {
  @override
  State<NetworkingExample> createState() => _NetworkingExampleState();
}

class _NetworkingExampleState extends State<NetworkingExample> {
  String _data = 'Press button to fetch data';

  Future<void> fetchData() async {
    try {
      final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
      if (response.statusCode == 200) {
        setState(() {
          _data = response.body;
        });
      } else {
        throw Exception('Failed to load data');
      }
    } catch (error) {
      setState(() {
        _data = 'Failed to load data: $error';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Networking Example'),
      ),
      body: Center(
        child: Text(_data),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: fetchData,
        child: Icon(Icons.cloud_download),
      ),
    );
  }
}
```

{% endtab %}

{% tab title="Result" %}

<figure><img src="/files/riUKoQaBYTXZGdrD17Nj" alt="" width="450"><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

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:

* [ ] Create a Flutter app that fetches and displays data from an API using a GET request.
* [ ] Implement a feature to create new data on the server using a POST request.
* [ ] Handle any errors that occur when sending requests and provide user feedback.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://flutteruniversity.gitbook.io/docs/learn-flutter/intermediate/networking.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
