Reputation: 3494
I am trying to learn dart, experimenting with http requests from this blog.
So I installed dart on Windows but for whatever reason I cant seem to run this script:
import 'dart:html';
import 'dart:convert';
void main() {
var data = { 'title' : 'My first post' };
HttpRequest.request(
'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
sendData: json.encode(data),
requestHeaders: {
'Content-Type': 'application/json; charset=UTF-8'
}
)
.then((resp) {
print(resp.responseUrl);
print(resp.responseText);
});
}
// Response
// https://jsonplaceholder.typicode.com/posts
// { "title": "My first post", "id": "101" }
When I run this from Windows terminal $dart run script.dart
this will error:
script.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
^
script.dart:8:3: Error: Undefined name 'HttpRequest'.
HttpRequest.request(
^^^^^^^^^^^
But in the blog post there is a link to dart pad where the code runs just fine. Any ideas to try? Thanks for any incite
$dart --version
Dart SDK version: 2.15.1 (stable) (Tue Dec 14 13:32:21 2021 +0100) on "windows_x64"
Upvotes: 1
Views: 4439
Reputation: 6701
Using the http package, is the preferred approach since it will work consistently on all platforms.
The same request can be made by doing the following:
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
var data = {'title': 'My first post'};
http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: json.encode(data),
).then((resp) {
print(resp.body);
});
}
Although typically async
/await
syntax is used instead:
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
var data = {'title': 'My first post'};
var resp = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: json.encode(data),
);
print(resp.body);
}
Upvotes: 2