首先导入第三方网络请求库dio
dio: ^2.1.3
-创建一个dart文件api里面存放项目的api
class HttpApi {
static final String BASE_URL = "";
///登录模块
static final String LOGIN_URL = BASE_URL + "";
///首页模块
//首页
static final String HOMEPAGE = BASE_URL + "";
}
-创建一个dart文件error
class ErrorBean {
final int code;
final String message;
ErrorBean(this.code, this.message);
}
主要部分,网络请求
-创建一个dart文件http,创建HttpManage类
1.定义请求方法
static final String GET = "get";
static final String POST = "post";
2.定义一个单例,初始化的时候可以设置网络请求的拦截器,请求成功的数据可以封装,因为例子返回data数据的字段不是固定的所以没有进行封装。回调方法用的Function这样可以统一处理特定的错误信息,本来想用接口实现,但是dart的抽象类不可以new,要用的话值能在Widget里面用implements所以放弃了。
static HttpManage _instance;
static HttpManage getInstance(){
if(_instance == null){
_instance = HttpManage();
}
return _instance;
}
HttpManage(){
dio = Dio(BaseOptions(
connectTimeout: 5000,
receiveTimeout: 100000,
));
}
3.写对应的GET和POST的方法只写了两个常用的网络请求
/**
* get获取数据
*/
get(String url, Map params, Function success, Function error) async {
_requestHttp(url, GET, params, success, error);
}
/**
* post 获取数据
*/
post(String url, Map params, Function success, Function error) async {
_requestHttp(url, POST, params, success, error);
}
/**
* 网络请求
*/
_requestHttp(String url, String method, Map params, Function success, Function error) async {
int code;
Response response;
if (method == GET) {
if (params != null && params.isNotEmpty) {
response = await dio.get(url, queryParameters: params);
} else {
response = await dio.get(url);
}
} else if (method == POST) {
if (params != null && params.isNotEmpty) {
response = await dio.post(url, queryParameters: params);
} else {
response = await dio.post(url);
}
}
String dataStr = json.encode(response.data);
Map dataMap = json.decode(dataStr);
code = dataMap["status"];
if(code == 200){
success(dataStr);
} else {
ErrorBean errorBean = ErrorBean(code, dataMap["message"]);
error(errorBean);
}
}
4.创建一个dart文件request,创建Request类里面写网络请求
class Request{
static login(String phone, String psw, Function success, Function error){
Map map = new Map();
map["mobile"] = phone;
map["password"] = psw;
HttpManage.getInstance().post(HttpApi.LOGIN_URL, map, success, error);
}
}
5.网络请求调用
Request.login(
mobile,
psw,
(String s){
},
(ErrorBean e){
},
);
6.贴一下页面完整的调用代码
class LoginVC extends StatefulWidget{
@override
State createState() {
// TODO: implement createState
return new _LoginState();
}
}
class _LoginState extends State {
FocusNode focusNode = new FocusNode();
FocusNode focusNode1 = new FocusNode();
String mobile, psw;
TextEditingController _unameController = new TextEditingController();
TextEditingController _pwdController = new TextEditingController();
GlobalKey _formKey= new GlobalKey();
@override
void initState() {
// TODO: implement initState
super.initState();
_unameController.addListener((){
mobile = _unameController.text;
});
_pwdController.addListener((){
psw = _pwdController.text;
});
}
void login(){
Request.login(
mobile,
psw,
(String s){
},
(ErrorBean e){
},
);
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text('登录'),
),
body: Padding(
padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24),
child: Form(
key: _formKey,
autovalidate: true,
child: Column(
children: [
TextFormField(
autofocus: false,
controller: _unameController,
decoration: InputDecoration(
labelText: "用户名",
hintText: "请输入手机号",
prefixIcon:Icon(Icons.person),
),
focusNode: focusNode,
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.go,
validator: (v){
return v.trim()
.length > 0 ? null : "手机号码不能为空";
},
),
TextFormField(
controller: _pwdController,
decoration: InputDecoration(
labelText: "密码",
hintText: "请输入密码",
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
focusNode: focusNode1,
validator: (v){
return v.trim()
.length > 5 ? null : "密码不能少于6位";
},
),
Padding(
padding: EdgeInsets.only(top: 28.0),
child: Row(
children: [
Expanded(
child: RaisedButton(
child: Text('登录'),
padding: EdgeInsets.all(15.0),
textColor: Colors.white,
color: Colors.blue,
onPressed: (){
if((_formKey.currentState as FormState).validate()){
focusNode.unfocus();
focusNode1.unfocus();
login();
}
},
))
],
),
)
],
),
),
)
);
}
}