import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';
//模拟登录页面
class GetPage extends StatefulWidget {
GetPage({Key? key}) : super(key: key);
@override
State<GetPage> createState() => _GetState();
}
class _GetState extends State<GetPage> {
String _getMsg = 'get';
String _postMsg = 'post';
get json => null;
//模拟接口 https://jd.itying.com/api/httpGet
_GetHttp() async {
var url = Uri.parse('https://jd.itying.com/api/httpGet');
var res = await http.get(url);
print('res:${res.body}');
print(res.body);
Map data = jsonDecode(res.body);
print(data['msg']);
setState(() {
this._getMsg = res.body;
});
}
//模拟接口 https://jd.itying.com/api/httpPost
_PostData() async {
var url = Uri.parse('https://jd.itying.com/api/httpPost');
var res = await http.post(url, body: {'username': 'xuan', 'age': '25'});
print(res.body);
setState(() {
this._postMsg = res.body;
});
}
// dio 请求 get;
_getDioHttp() async {
try {
var res = await Dio().get('https://jd.itying.com/api/httpPost');
print(res);
} catch (e) {
print(e);
}
}
_postDioHttp() async {
try {
var res = await Dio().post('https://jd.itying.com/api/httpPost',
data: {'username': 'xuan', 'age': '25'});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
child: GestureDetector(
onTap: () => _GetHttp(),
child: Container(
width: 150,
height: 30,
decoration: BoxDecoration(color: Colors.green),
child: Text('发起Get请求'),
),
),
),
Container(
child: Text('${_getMsg}'),
),
Container(
child: GestureDetector(
onTap: () => _PostData(),
child: Container(
width: 150,
height: 30,
decoration: BoxDecoration(color: Colors.green),
child: Text('发起poost请求'),
),
),
),
Container(
child: Text('${_postMsg}'),
),
Container(
child: Column(
children: [
Container(
child: YshContent(),
)
],
),
)
],
),
);
}
}
class YshContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
labelText: "请输入用户名",
// icon: Icon(Icons.people),
hintText: "请输入用户名",
prefixIcon: Icon(Icons.people_alt_rounded)),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
obscureText: true,
decoration: InputDecoration(
labelText: "请输入密码",
prefixIcon: Icon(Icons.lock),
hintText: "请输入密码",
),
),
),
],
);
}
}
//请求要安装http插件 : http:^0.13.1
/**
* dio请求中的参数方法:
* path :发起请求的链接
* data :发起请求时要携带的数据,如:FromData
* queryParameters :参数查询
* Option:请求选项
* cancelToken:用来取消发送请求的token
* onSendProgress:网络请求发送的进度
* on ReceiveProgress:网络请求接收的进度
*/
这个代码时模拟的登录页面的请求以及返回结果适合简单的刚入门的看一下,如果你要用的话可以在把这个代码抽离出去然后进行一个封装,有不对的地方请大家指正;