Learn Dart #8: Perform a server-side POST request in under 30 seconds

creativ_bracket

Jermaine

Posted on November 22, 2018

Learn Dart #8: Perform a server-side POST request in under 30 seconds

Hello friends. In today's quick tip we will be using the inbuilt HttpClient class to perform a server-side POST request.

This is demonstrated in the below video:

ā†’ Watch on YouTube


Below is the full solution:

I'll admit it's a bit verbose. However the Dart team created a library called http to simplify this logic.

To install, update your pubspec.yaml file:

name: dart_project
dependencies:
  http: ^0.12.0
Enter fullscreen mode Exit fullscreen mode

And run pub get to update your dependencies.

Here's what the solution now looks like:

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

void main() async {
  var response = await http.post('https://jsonplaceholder.typicode.com/posts',
    body: {
      'title': 'Post 1',
      'content': 'Lorem ipsum dolor sit amet',
    });

  print(response.body);
}
Enter fullscreen mode Exit fullscreen mode

And run:

$ dart bin/main.dart

# Result:
# {
#   "title": "Post 1",
#   "content": "Lorem ipsum dolor sit amet",
#   "id": 101
# }
Enter fullscreen mode Exit fullscreen mode

Subscribe to my YouTube channel for more videos covering various aspects of full-stack web development.

Like, share and follow me šŸ˜ for more content on Dart.

Further reading

šŸ’– šŸ’Ŗ šŸ™… šŸš©
creativ_bracket
Jermaine

Posted on November 22, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related