1. 数据类型转换
服务端请求回来的数据都是JSON类型的,为了可以对数据进行遍历,必须要转成Map类型的。
在需要格式转换的文件中引入依赖包。
import 'dart:convert';
Map类型转换成JSON类型。
Map userInfo={"username":"张三","age":20};
print(userInfo is Map);
// true
var user = json.encode(userInfo);
// 把Map类型转为Json类型
print(user is String);
// true
JSON类型转成Map类型。
String studentInfo='{"student_name":"李四","age":20}';
print(studentInfo is String);
// true
var student = json.decode(studentInfo);
// 把Map类型转为Json类型
print(student is Map);
// true
2. 安装网络请求插件
配置http插件。
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
date_format: ^1.0.6
flutter_cupertino_date_picker: ^1.0.26+2
flutter_swiper: ^1.1.6
fluttertoast: ^7.1.6
# 网络请求
http: ^0.12.2
在pubspec.yaml中配置保存后,在VS Code环境中会自动下载依赖包。
如果无法正常下载,执行 flutter pub get 。
参考: https://pub.flutter-io.cn/packages/http
3. Get请求
// 引入格式转换依赖
import 'dart:convert';
import 'package:flutter/material.dart';
// 引入网格请求插件
import 'package:http/http.dart' as Http;
class GetPage extends StatefulWidget {
GetPage({Key key}) : super(key: key);
@override
_GetPageState createState() => _GetPageState();
}
class _GetPageState extends State<GetPage> {
String _news="";
@override
void initState() {
super.initState();
}
// Get请求
void _getData() async{
var url = "接口地址";
var result = await Http.get(url);
if(result.statusCode==200){
setState(() {
this._news=json.decode(result.body);
});
}else{
print(result.statusCode);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title: Text("GET请求"),
),
body:Center(
child:Column(
children:<Widget>[
Text(this._news),
RaisedButton(
child: Text("发起请求"),
onPressed:_getData
),
],
)
)
);
}
}
4. Post请求
// 引入格式转换依赖
import 'dart:convert';
import 'package:flutter/material.dart';
// 引入网格请求插件
import 'package:http/http.dart' as Http;
class PostPage extends StatefulWidget {
PostPage({Key key}) : super(key: key);
@override
_PostPageState createState() => _PostPageState();
}
class _PostPageState extends State<PostPage> {
// POST请求
void _postData() async{
var url = "接口地址";
var data={'username':'张三','age':20};
var result = await Http.post(url,body:data);
if(result.statusCode==200){
print(json.decode(result.body));
}else{
print(result.statusCode);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title: Text("POST请求"),
),
body:Center(
child: RaisedButton(
child: Text("发起请求"),
onPressed:_postData
),
)
);
}
}
5. 请求示例
// 引入格式转换依赖
import 'dart:convert';
import 'package:flutter/material.dart';
// 引入网格请求插件
import 'package:http/http.dart' as Http;
class HttpPage extends StatefulWidget {
HttpPage({Key key}) : super(key: key);
@override
_HttpPageState createState() => _HttpPageState();
}
class _HttpPageState extends State<HttpPage> {
List _list = [];
@override
void initState() {
super.initState();
this._getData();
}
// 获取数据
void _getData() async{
var url = "http://a.itying.com/api/productlist";
var result = await Http.get(url);
if(result.statusCode == 200){
print(result.body);
setState(() {
this._list = json.decode(result.body)["result"];
});
}else{
print("请求失败");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title: Text("HTTP请求"),
),
// 渲染数据(第一种方式)
// body:this._list.length==0?Center(child:Text("加载中")):ListView(
// children:this._list.map((obj){
// return ListTile(
// title: Text(obj["title"]),
// );
// }).toList()
// )
// 渲染数据(第二种方式)
body:this._list.length==0?Center(child: Text("加载中")):ListView.builder(
itemCount:this._list.length,
itemBuilder:(context,index){
return ListTile(
title:Text("${this._list[index]['title']}")
);
}
)
);
}
}