flutter

Send HTTP POST request in Flutter or Dart

If you want to send an HTTP Post request in Flutter or Dart, you can use the code examples explained in this post.

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

void main() async {
    http.Response response = await createUser("Bob", "engineer");
    
    print(response.body);
}

Future<http.Response> createUser(String name, String job) {
    return http.post(
        Uri.parse('https://reqres.in/api/users'),
        headers: <String, String>{
            'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
            'name': name,
            'job': job
        }),
    );
}

Output

{
   "name":"Bob",
   "job":"engineer",
   "id":"952",
   "createdAt":"2022-02-28T14:39:42.204Z"
}

We are using package 'package:http/http.dart' to send a post request in Flutter. We are also sending data in our post request and getting the response in the response named variable.

We have created a Future function createUser() that takes two parameters name and job. Inside this function, we are using http.post() to send the POST request. In the header of the post request, we are sending content-type header.

If you are developing for the android platform, you need to add the user permission in AndroidManifest.xml file. The location of the manifest file is:

android/app/src/main/AndroidManifest.xml

The user permission code to be added to the manifest file is:

<uses-permission android:name="android.permission.INTERNET"/>
Was this helpful?