DEV Community

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

Posted on • Originally published at creativebracket.com

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

Top comments (0)