DEV Community

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

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

graphicbeacon profile image Jermaine Oppong Originally published at creativebracket.com ・1 min read

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

Discussion (0)

pic
Editor guide