Paramclasses Academy - Blog

Tutorials Details

←
Post 26 of 40
→

Flutter HTTP Requests Explained: GET, POST, PUT and DELETE

Flutter HTTP Requests Explained: GET, POST, PUT and DELETE

November 3, 2026

❖ Flutter HTTP Requests Explained: GET, POST, PUT and DELETE

❖ Welcome to Param Classes!

Welcome to another practical Flutter App Development tutorial at Param Classes!

In our previous tutorial, we learned how to connect a Flutter application to a REST API and fetch JSON data from a server.

Now, we will take the next step and understand four important HTTP methods: GET, POST, PUT, and DELETE.

These methods are used in almost every modern application.

For example, imagine you are developing a Student Management Application. You want to:

  • Display all student records.

  • Register a new student.

  • Update existing student details.

  • Delete a student record.

All these operations can be performed through HTTP requests.

In this tutorial, we will learn each method with practical Flutter examples using the HTTP package.

✦ 1. What Are HTTP Requests in Flutter?

HTTP stands for Hypertext Transfer Protocol.

It is a communication protocol that allows applications to exchange information over a network.

A Flutter application can send an HTTP request to a backend server. The server processes the request and returns a response.

For example:

Flutter App → HTTP Request → REST API → Backend Server → HTTP Response → Flutter App

The HTTP package helps Flutter developers perform these operations.

Install it using:

flutter pub add http

Import the package:

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

Official documentation:

https://pub.dev/packages/http

✦ 2. Understand the Four Important HTTP Methods

Before writing code, understand the purpose of each method.

Method Purpose Example
GET Fetch data Display students
POST Create data Register student
PUT Update data Edit student
DELETE Remove data Delete student

Let's understand each method practically.

✦ 3. GET Request in Flutter — Fetch Data

GET is used to retrieve information from a server.

For this example, we will use the JSONPlaceholder testing API.

API URL:

https://jsonplaceholder.typicode.com/posts

Create a function:

Future<void> getPosts() async {

  try {

    final response = await http.get(
      Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    );

    if (response.statusCode == 200) {

      final data = jsonDecode(response.body);

      print(data);

    } else {

      print('Failed: ${response.statusCode}');

    }

  } catch (e) {

    print('Error: $e');

  }
}

Explanation:

  • http.get() sends a GET request.

  • Uri.parse() converts the API URL into a URI.

  • await waits for the server response.

  • response.statusCode checks the HTTP response code.

  • jsonDecode() converts JSON text into Dart data.

If the request is successful, the server returns the post information.

✦ 4. POST Request in Flutter — Insert Data

POST is used to send new information to a server.

For example, suppose a student wants to register for a Flutter course.

We need to send the student's name and course to the API.

Example code:

Future<void> addPost() async {

  try {

    final response = await http.post(

      Uri.parse('https://jsonplaceholder.typicode.com/posts'),

      headers: {
        'Content-Type': 'application/json',
      },

      body: jsonEncode({

        'title': 'Flutter Tutorial',

        'body': 'Learning HTTP requests in Flutter',

        'userId': 1,

      }),

    );

    if (response.statusCode == 201) {

      print('Data inserted successfully');

      print(response.body);

    } else {

      print('Insert failed');

    }

  } catch (e) {

    print('Error: $e');

  }
}

Explanation:

  • http.post() sends new data to the server.

  • headers specify the content type.

  • jsonEncode() converts Dart data into JSON.

  • body contains the data being sent.

  • Status code 201 commonly indicates that a resource was created.

Note: JSONPlaceholder is a testing API. It simulates creating data but does not permanently save new records.

✦ 5. PUT Request in Flutter — Update Data

PUT is commonly used to replace or update an existing resource.

Suppose a student changes their course from PHP to Flutter.

We can send updated information using a PUT request.

Example API URL:

https://jsonplaceholder.typicode.com/posts/1

Code:

Future<void> updatePost() async {

  try {

    final response = await http.put(

      Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),

      headers: {
        'Content-Type': 'application/json',
      },

      body: jsonEncode({

        'id': 1,

        'title': 'Updated Flutter Course',

        'body': 'Updated post information',

        'userId': 1,

      }),

    );

    if (response.statusCode == 200) {

      print('Data updated successfully');

      print(response.body);

    } else {

      print('Update failed');

    }

  } catch (e) {

    print('Error: $e');

  }
}

Explanation:

  • http.put() sends an update request.

  • The URL contains the record ID.

  • jsonEncode() converts the updated information into JSON.

  • The server returns the result.

In a real application, the backend decides how PUT updates the resource. PUT commonly represents replacing the resource, while PATCH is generally used for partial updates.

✦ 6. DELETE Request in Flutter — Remove Data

DELETE is used to remove a record from a server.

For example, suppose you want to delete student record number 1.

API URL:

https://jsonplaceholder.typicode.com/posts/1

Code:

Future<void> deletePost() async {

  try {

    final response = await http.delete(

      Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),

    );

    if (response.statusCode == 200 ||
        response.statusCode == 204) {

      print('Data deleted successfully');

    } else {

      print('Delete failed');

    }

  } catch (e) {

    print('Error: $e');

  }
}

Explanation:

  • http.delete() sends a delete request.

  • The URL identifies the record.

  • Status code 200 or 204 can indicate successful deletion.

The exact success status depends on the backend API.

✦ 7. Create a Complete Flutter HTTP Request Demo

Now let's combine all four methods in one beginner-friendly Flutter application.

This application will contain four buttons:

  1. GET — Fetch data.

  2. POST — Insert data.

  3. PUT — Update data.

  4. DELETE — Delete data.

Open lib/main.dart and paste this complete code:

import 'dart:convert';

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HttpDemoScreen(),
    );
  }
}

class HttpDemoScreen extends StatefulWidget {
  const HttpDemoScreen({super.key});

  @override
  State<HttpDemoScreen> createState() => _HttpDemoScreenState();
}

class _HttpDemoScreenState extends State<HttpDemoScreen> {

  String result = 'Click a button to test HTTP requests';

  bool loading = false;

  final String baseUrl =
      'https://jsonplaceholder.typicode.com/posts';

  Future<void> getData() async {

    await sendRequest('GET');

    try {

      final response = await http.get(Uri.parse(baseUrl));

      setState(() {
        result = response.body;
      });

    } catch (e) {

      setState(() {
        result = 'GET Error: $e';
      });

    } finally {

      setState(() {
        loading = false;
      });

    }
  }

  Future<void> postData() async {

    await performRequest(() async {

      final response = await http.post(

        Uri.parse(baseUrl),

        headers: {
          'Content-Type': 'application/json',
        },

        body: jsonEncode({

          'title': 'New Flutter Post',

          'body': 'This is a POST request example',

          'userId': 1,

        }),

      );

      return response;

    });

  }

  Future<void> putData() async {

    await performRequest(() async {

      final response = await http.put(

        Uri.parse('$baseUrl/1'),

        headers: {
          'Content-Type': 'application/json',
        },

        body: jsonEncode({

          'id': 1,

          'title': 'Updated Flutter Post',

          'body': 'This is updated information',

          'userId': 1,

        }),

      );

      return response;

    });

  }

  Future<void> deleteData() async {

    await performRequest(() async {

      final response = await http.delete(
        Uri.parse('$baseUrl/1'),
      );

      return response;

    });

  }

  Future<void> sendRequest(String method) async {

    setState(() {
      loading = true;
      result = 'Loading...';
    });

  }

  Future<void> performRequest(
    Future<http.Response> Function() request,
  ) async {

    setState(() {
      loading = true;
      result = 'Loading...';
    });

    try {

      final response = await request();

      setState(() {

        result =
            'Status Code: ${response.statusCode}\n\n'
            '${response.body}';

      });

    } catch (e) {

      setState(() {
        result = 'Error: $e';
      });

    } finally {

      setState(() {
        loading = false;
      });

    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(
        title: const Text('Flutter HTTP Demo'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),

      body: Padding(

        padding: const EdgeInsets.all(16),

        child: Column(

          children: [

            Wrap(

              spacing: 10,
              runSpacing: 10,

              children: [

                ElevatedButton(
                  onPressed: loading ? null : getData,
                  child: const Text('GET'),
                ),

                ElevatedButton(
                  onPressed: loading ? null : postData,
                  child: const Text('POST'),
                ),

                ElevatedButton(
                  onPressed: loading ? null : putData,
                  child: const Text('PUT'),
                ),

                ElevatedButton(
                  onPressed: loading ? null : deleteData,
                  child: const Text('DELETE'),
                ),

              ],

            ),

            const SizedBox(height: 20),

            if (loading)
              const CircularProgressIndicator(),

            const SizedBox(height: 20),

            Expanded(

              child: SingleChildScrollView(

                child: SelectableText(result),

              ),

            ),

          ],

        ),

      ),

    );

  }
}

Important: In this example, sendRequest() sets the loading state for GET. The POST, PUT, and DELETE operations use performRequest() to manage loading, errors, and responses.

For a production application, you can simplify the code by using one common request-handling method for all four operations.

✦ 8. Understand HTTP Status Codes

When Flutter sends a request, the server returns an HTTP status code.

Some commonly used status codes are:

Status Code Meaning
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

For example, if the API returns 404, the requested resource may not exist.

Understanding status codes helps developers identify API problems.

✦ 9. Difference Between PUT and PATCH

Beginners often confuse PUT and PATCH.

Both methods are used to update information, but their typical purposes are different.

PUT: Usually replaces the complete resource.

PATCH: Usually updates only selected fields.

For example, a student record contains:

  • Name

  • Mobile

  • Course

If you send all fields to update the record, you may use PUT.

If you only want to update the course, you may use PATCH.

Example:

final response = await http.patch(

  Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),

  headers: {
    'Content-Type': 'application/json',
  },

  body: jsonEncode({
    'title': 'Updated Title',
  }),

);

✦ 10. Common Mistakes Beginners Should Avoid

While working with HTTP requests, beginners may face these common problems:

1. Forgetting the HTTP package

Always install the package before importing it.

2. Incorrect API URL

Check the URL carefully before sending requests.

3. Forgetting JSON encoding

Use jsonEncode() when sending JSON request bodies.

4. Not checking status codes

Always check the server response before displaying success messages.

5. Ignoring exceptions

Use try-catch to handle network errors.

6. Calling APIs inside build()

Avoid sending requests directly from the widget's build() method. Use initState() or an appropriate event handler.

7. Not showing loading indicators

Give users feedback while a request is being processed.

✦ 11. Practical Assignment for Beginners

Now build your own Student CRUD Application using Flutter HTTP Requests.

Your application should contain:

  1. Student Registration Form.

  2. Student Name field.

  3. Mobile Number field.

  4. Course field.

  5. Save Student button using POST.

  6. Student List using GET.

  7. Edit Student button using PUT.

  8. Delete Student button using DELETE.

  9. Loading indicator.

  10. Error message handling.

Connect this application to your own REST API when you are ready to work with a PHP and MySQL backend.

❖ Conclusion

HTTP requests are an essential part of Flutter application development.

GET, POST, PUT, and DELETE allow Flutter applications to communicate with backend servers and perform CRUD operations.

In this tutorial, we learned how to fetch data, send new information, update existing records, and delete data using the HTTP package.

At Param Classes, we believe that practical coding is one of the best ways to understand application development. Practice each HTTP method and try building your own Student CRUD Application.

In the next tutorial, we will learn how to connect Flutter with PHP and MySQL using REST APIs.

Keep Learning, Keep Building with Param Classes!

←
Post 26 of 40
→