Hello friends. In today’s quick tip we will be using the inbuilt HttpClient
class to perform a server-side POST request.
Below is the full solution:
import 'dart:io'; import 'dart:convert'; main() async { var apiUrl = Uri.parse('https://jsonplaceholder.typicode.com/posts'); var client = HttpClient(); // `new` keyword optional // 1. Create request HttpClientRequest request = await client.postUrl(apiUrl); // 2. Add payload to request var payload = { 'title': 'Post 1', 'content': 'Lorem ipsum dolor sit amet', }; request.write(json.encode(payload)); // 3. Send the request HttpClientResponse response = await request.close(); // 4. Handle the response var resStream = response.transform(Utf8Decoder()); await for (var data in resStream) { print('Received data: $data'); } }
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
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); }
And run:
dart bin/main.dart # Result: # { # "title": "Post 1", # "content": "Lorem ipsum dolor sit amet", # "id": 101 # }
Further reading
Sharing is caring 
If you enjoyed reading this post, please share this through the various social buttons hovering on the left/top side of the screen . Also, check out and subscribe to my YouTube channel (hit the bell icon too) for videos on Dart.
Subscribe to the newsletter for my free 35-page Get started with Dart eBook and to be notified when new content is released.
Like, share and follow me for more content on Dart.