0
0
FlutterHow-ToBeginner · 3 min read

How to Make POST Request in Flutter: Simple Guide

To make a POST request in Flutter, use the http.post() method from the http package, passing the URL and the body data as a map. This sends data to a server and returns a response you can handle asynchronously.
📐

Syntax

The http.post() method sends data to a server. It requires a Uri for the URL and a Map<String, String> for the body data. You can also add headers if needed.

  • Uri.parse(url): Converts the URL string to a Uri object.
  • body: The data sent in the request, usually as a map.
  • headers: Optional, to specify content type or authorization.
dart
final response = await http.post(
  Uri.parse('https://example.com/api'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'key': 'value'}),
);
💻

Example

This example shows how to send a POST request with JSON data to a test API and print the response status and body.

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  Future<void> sendPostRequest() async {
    final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
    final response = await http.post(
      url,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'title': 'foo', 'body': 'bar', 'userId': 1}),
    );
    print('Status code: ${response.statusCode}');
    print('Response body: ${response.body}');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('POST Request Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: sendPostRequest,
            child: Text('Send POST Request'),
          ),
        ),
      ),
    );
  }
}
Output
Status code: 201 Response body: {"title":"foo","body":"bar","userId":1,"id":101}
⚠️

Common Pitfalls

Common mistakes when making POST requests in Flutter include:

  • Not encoding the body data as JSON when the server expects JSON.
  • Forgetting to set the Content-Type header to application/json.
  • Using a plain string or map without jsonEncode for the body.
  • Not awaiting the http.post() call, causing unexpected behavior.

Always check the server API documentation for required headers and body format.

dart
/* Wrong way: sending map directly without encoding and missing header */
final response = await http.post(
  Uri.parse('https://example.com/api'),
  body: {'key': 'value'},
);

/* Right way: encode body and set header */
final response = await http.post(
  Uri.parse('https://example.com/api'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'key': 'value'}),
);
📊

Quick Reference

Tips for making POST requests in Flutter:

  • Use http.post() with Uri.parse() for the URL.
  • Encode your body data with jsonEncode() if sending JSON.
  • Set Content-Type header to application/json when sending JSON.
  • Always await the request to handle the response properly.
  • Handle errors by checking response.statusCode.

Key Takeaways

Use the http package's post() method with Uri.parse() to send POST requests.
Always encode your body data with jsonEncode() when sending JSON.
Set the Content-Type header to application/json for JSON data.
Await the post() call to get the server response correctly.
Check response status code to handle success or errors.