Flutter Http POST request

So, I have created a form for my project, how do I send the user input to the database?

When the form only has one or two questions such as login form, it’s easy to transfer user input. However, many forms have multiple questions. It will be a lot easier to transfer information with a data transfer object.

Let’s have simple class to see how this work,

class User {

  String userName;

  String address;

  String zipCode;

  String city;

  String state;

User (this.userName, this.address, this.zipCode , this.city, this.state}

With the User class, you can create a user object and whenever user enter the information, you can store with it.

final newUser = User( );

This newUser will be your data transfer object to store information. For example,

newUser.userName = “Emily K

What next?

This depends on how you are going to store your data in database. Here I’m going to send my data to a POST api since this is what we are doing with our project.

Convert Object to JSON

Before I can transfer the information from my object, I need to convert it to JSON. You can use dart:convert libray’s built in jsonEncode() function to convert user object to JSON. But if you call jsonEncode() without creating toJson() method, you will get an error. Remember the User class we created earlier, I want you to add toJson() method there.

class User {

  …………………

  Map toJson() => {

        “userName”: userName,

        “address”: address,

        “zipCode”: zipCode,

        “city”: city,

        “state”: state,

      };

}

Now you are ready to convert your object to JSON. In the you are converting the object, import ‘dart: convert’; Assuming you already store all information for newUser object, here is how you can use jsonEncode():

String jsonUser = jsonEncode(newUser);

You don’t need to call toJson( ) here because jsonEncode will call toJson( ) for you.

Send data to the internet

In Flutter documentation, you can follow https://docs.flutter.dev/cookbook/networking/send-data using http package to send your data to an API. Their example use {JSON} placeholder, free fake API for testing and prototyping. This method will work for most API but it did not work for the API we created.

What happen???

My post request was rejected because my request body wasn’t JSON. What??? Didn’t I just change my object to JSON in the above steps? I verified my jsonUser online, it is a valid JSON and I have specified headers: {“Content-Type”:”application/json”}.

What they didn’t tell you?

It turns out when you use the http package, it changes the request body to application/json ; charset=utf-8. The server doesn’t expect to see the suffix so it’s being rejected.

Now what?

You can contact the server to have the API accept “application/json ; charset=utf-8” or you can use HttpClient.

In you file,

import ‘dart:convert’;

import ‘dart:io’;

import ‘dart:async’;

Example code:

  Future<void> submitPostForm() async {

    String Url = ‘https://someapi.wn.r.appspot.com/’

    HttpClient httpClient = HttpClient();

    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

    request.headers.set(‘content-type’, ‘application/json’);

    request.add(utf8.encode(jsonEncode(newUser)));

    HttpClientResponse response = await request.close();

 ..codes to handle response

  }

Tada!!! 201 Created!

Leave a comment

Your email address will not be published. Required fields are marked *