我正在嘗試學習飛鏢,試驗來自這個博客的 http 請求。
因此,我在 Windows 上安裝了 dart,但無論出于何種原因,我似乎都無法運行此腳本:
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" }
當我從 Windows 終端運行它時,$dart run script.dart這將出錯:
script.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
^
script.dart:8:3: Error: Undefined name 'HttpRequest'.
HttpRequest.request(
^^^^^^^^^^^
但是在博客文章中有一個飛鏢墊的鏈接,代碼運行得很好。有什么想法可以嘗試嗎?感謝任何煽動
$dart --version
Dart SDK version: 2.15.1 (stable) (Tue Dec 14 13:32:21 2021 0100) on "windows_x64"
uj5u.com熱心網友回復:
使用http包是首選方法,因為它可以在所有平臺上始終如一地作業。
可以通過執行以下操作來發出相同的請求:
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);
});
}
盡管通常使用async/await語法來代替:
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420870.html
標籤:
上一篇:改變值onTap
