πŸ—Ό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:

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:

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

Complete Example Code πŸ“œ

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

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),
      ),
    );
  }
}

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