json格式处理
引入内置库
import 'dart:convert';
map和json类型转换
List<Map> videoInfo=[
{
"video_id":"aaa111",
"name":"vue精选视频",
"coverSrc":"https://www.baidu.com/img1"
},
{
"video_id":"aaa112",
"name":"python精选视频",
"coverSrc":"https://www.baidu.com/img2"
},
];
var a=json.encode(videoInfo);//map转为json字符串
var b=json.decode(a)//json字符串转为map
print(a is String);//true
print(b[0] is Map);//true
RESTful
安装http官方库
库地址
http: ^0.12.0+4
get获取数据
Widget build(BuildContext context) {
return Container(
child: RaisedButton(onPressed: () async{
var url = 'http://192.168.1.14:8787/getUri';
var result = await http.get(url);
if (result.statusCode == 200) {//请求成功
var jsonResponse = json.decode(result.body);
print(jsonResponse);
} else {//请求失败
print('Request failed with status: ${result.statusCode}.');
}
},child: new Text('get请求数据'),),
);
}
post提交数据
RaisedButton(
onPressed: () async {
var url = 'http://192.168.1.14:8787/postUri';
var body = {"name": "123", "age": '18'};
var result = await http.post(url, body: body);
if (result.statusCode == 200) {
//请求成功
var jsonResponse = json.decode(result.body);
print(jsonResponse);
} else {
//请求失败
print('Request failed with status: ${result.statusCode}.');
}
},
child: new Text('post提交数据'),
)
Dio
下载第三方Dio库
官方介绍
dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等…
中文地址
dio: ^3.0.9
引入方式
import 'package:dio/dio.dart';
Widget build(BuildContext context) {
return Column(children: <Widget>[
RaisedButton(
onPressed: () async {
Response response = await Dio().post(
'http://192.168.1.14:8787/postUri',
data: {
"name":"小明",
"age":"18"
}
);
print(response.data);
},
child: new Text('dio'),
),
]);