dart网络请求
一、请求本地自己编写的json文件
我这取名叫shop.json
{
"data": [
{
"name": "?��",
"image": "https://img-blog.csdnimg.cn/dd7ef8859850417ab6f20b36d7276ab0.png",
"oriPrice": 14,
"presentPrice": 20,
"goodsID": "001"
}
]
}
打开git输入
npx json-server shop.json
二、dart io发起请求
1.1.get请求
import 'dart:io';
import 'dart:convert';
main(){
_get();
}
_get() async{
var responseBody;
var httpClient = new HttpClient();
var requset = await httpClient.getUrl(Uri.parse("http://localhost:3000/data"));
var response = await requset.close();
if(response.statusCode == 200){
responseBody = await response.transform(utf8.decoder).join();
print(responseBody);
}else{
print("error");
}
}
dio请求
在平时开发中最好用dio库和http库,因为dart io中是使用HttpClient发起的请求,HttpClient本身功能较弱,很多常用功能不支持。
在pubspec.yaml添加依赖:
dio: ^2.0.14
dio_post() async{
try{
Response response;
response = await Dio().post("http://localhost:3000/data");
if(response.statusCode == 200){
print(response);
}else{
print("error");
}
}catch(e){
print(e);
}
}
http_get() async{
try{
var response = await my_http.get("http://localhost:3000/data");
if(response.statusCode == 200){
print(response.body);
}else{
print("error");
}
}catch(e){
print(e);
}
}
官网 由于weui不支持flutter2.0及以上版本,特开发替代版本tdui,官网:https://tdui.td0f7.cn/
|