YSNetWork.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart';
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_tzh/login/YSLogin.dart';
  6. import 'package:fluttertoast/fluttertoast.dart';
  7. // import 'package:fluttertoast/fluttertoast.dart';
  8. import 'package:shared_preferences/shared_preferences.dart';
  9. import 'YSTools.dart';
  10. //http://192.168.1.22:8888
  11. //http://114.115.251.233:30034
  12. String base = 'http://114.115.251.233:30034/api';
  13. int outTime = 50000;
  14. enum RequestType{
  15. put,
  16. delete,
  17. get,
  18. post
  19. }
  20. class YSNetWork{
  21. int outTime = 20000;
  22. static ysRequestHttp(BuildContext context,{required RequestType type,required String api,required dynamic parameter,bool isLoading = false,bool isToken = true,required ValueSetter successSetter}) async{
  23. if(isLoading==false){
  24. int outTime = 20000;
  25. String url = '$base$api';
  26. SharedPreferences prefs = await SharedPreferences.getInstance();
  27. String token = prefs.getString('token')??'';
  28. // LogUtil.d('请求token:$token');
  29. Map<String, dynamic> httpHeaders = {
  30. 'Accept': 'application/json,*/*',
  31. 'Content-Type': 'application/json',
  32. if(isToken==true)'Authorization': 'Bearer $token'
  33. };
  34. LogUtil.d('请求头 $httpHeaders');
  35. try {
  36. LogUtil.d('请求网址:$url\n请求参数:$parameter');
  37. Response response;
  38. if(type==RequestType.put){
  39. response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  40. }else if(type==RequestType.post){
  41. response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  42. }else if(type==RequestType.delete){
  43. response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  44. }else{
  45. response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
  46. }
  47. // LogUtil.d('请求网址:$url\n请求结果:${response.data}');
  48. Map dict = response.data;
  49. LogUtil.d('请求网址:$url\n请求结果:$dict');
  50. if(dict['code']==200){
  51. successSetter(dict);
  52. }else if(dict['code']==401){
  53. ysFlutterToast('${dict['msg']??''}');
  54. prefs.remove('token');
  55. // ignore: use_build_context_synchronously
  56. Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
  57. return const YSLogin();
  58. }), (route) => false);
  59. }else{
  60. ysFlutterToast('${dict['msg']??''}');
  61. }
  62. } catch (error) {
  63. LogUtil.d('请求网址:$url\n网络错误:$error');
  64. }
  65. }else{
  66. ysShowCenterAlertView(context, YSNetWorkView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){},successSetter: (value){
  67. successSetter(value);
  68. },),isTrans: true);
  69. }
  70. }
  71. static ysRequestHttp2(BuildContext context,{required RequestType type,required String api,required dynamic parameter,bool isLoading = false,bool isToken = true,required
  72. ValueSetter imageSetter,required ValueSetter successSetter}) {
  73. FocusScope.of(context).unfocus();
  74. ysShowCenterAlertView(context, YSImageUploadView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){
  75. imageSetter(value);
  76. },successSetter: (value){
  77. successSetter(value);
  78. }),isTrans: true);
  79. }
  80. }
  81. void ysFlutterToast(String msg,{bool isCenter = false}){
  82. Fluttertoast.showToast(
  83. msg: msg,
  84. gravity: isCenter?ToastGravity.CENTER:ToastGravity.BOTTOM,
  85. textColor: Colors.white,
  86. backgroundColor: Colors.black87,
  87. timeInSecForIosWeb: 2,
  88. );
  89. }
  90. class YSNetWorkView extends StatefulWidget {
  91. final ValueSetter successSetter;
  92. final ValueSetter imageSetter;
  93. final RequestType type;
  94. final String api;
  95. final dynamic parameter;
  96. final bool isLoading;
  97. final bool isToken;
  98. final bool isImage;
  99. const YSNetWorkView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
  100. required this.imageSetter,this.isImage = false, required this.successSetter}) : super(key: key);
  101. @override
  102. YSNetWorkViewState createState() => YSNetWorkViewState();
  103. }
  104. class YSNetWorkViewState extends State<YSNetWorkView> {
  105. bool _isError = false;
  106. @override
  107. void initState() {
  108. Future.delayed(const Duration(seconds: 0)).then((value) async{
  109. Map dict = await _getData();
  110. if(dict.isNotEmpty){
  111. widget.successSetter(dict);
  112. }
  113. });
  114. super.initState();
  115. }
  116. _getData() async{
  117. String url = '$base${widget.api}';
  118. SharedPreferences prefs = await SharedPreferences.getInstance();
  119. String token = prefs.getString('token')??'';
  120. Map<String, dynamic> httpHeaders = {
  121. 'Accept': 'application/json,*/*',
  122. 'Content-Type': 'application/json',
  123. if(widget.isToken==true)'Authorization': 'Bearer $token'
  124. };
  125. try {
  126. LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
  127. Response response;
  128. if(widget.type==RequestType.put){
  129. response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  130. }else if(widget.type==RequestType.post){
  131. response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  132. }else if(widget.type==RequestType.delete){
  133. response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  134. }else{
  135. response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
  136. }
  137. LogUtil.d('请求网址:$url\n请求结果:${response.data}');
  138. Map dict = response.data;
  139. if(!mounted)return;
  140. Navigator.pop(context);
  141. if(dict['code']==200){
  142. return dict;
  143. }else if(dict['code']==401){
  144. ysFlutterToast('${dict['msg']??''}');
  145. if (!mounted) return;
  146. Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
  147. return const YSLogin();
  148. }), (route) => false);
  149. prefs.remove('token');
  150. return {};
  151. }else{
  152. ysFlutterToast('${dict['msg']??''}');
  153. return {};
  154. }
  155. } catch (error) {
  156. if (!mounted) return;
  157. Navigator.pop(context);
  158. _isError = true;
  159. setState(() {});
  160. LogUtil.d('请求网址:$url\n网络错误:$error');
  161. return {};
  162. }
  163. }
  164. @override
  165. Widget build(BuildContext context) {
  166. return WillPopScope(
  167. onWillPop: () async{
  168. return false;
  169. },
  170. child: widget.isLoading==false?Container():Center(
  171. child: Container(
  172. height: hsp(150),
  173. width: hsp(150),
  174. decoration: const BoxDecoration(
  175. borderRadius: BorderRadius.all(Radius.circular(5)),
  176. color: Colors.black45,
  177. ),
  178. alignment: Alignment.center,
  179. child: Column(
  180. mainAxisSize: MainAxisSize.min,
  181. children: [
  182. SizedBox(
  183. width: 60,
  184. height: 60,
  185. child: _isError==true?const Icon(
  186. Icons.error_outline,size: 60,color: Colors.redAccent,
  187. ):CupertinoActivityIndicator(
  188. radius: hsp(20),
  189. color: Colors.white,
  190. ),
  191. ),
  192. Container(
  193. margin: EdgeInsets.only(top: hsp(15)),
  194. child: Text(_isError==true?'出错了':'请求中',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
  195. )
  196. ],
  197. ),
  198. ),
  199. ),
  200. );
  201. }
  202. }
  203. class YSImageUploadView extends StatefulWidget {
  204. final ValueSetter successSetter;
  205. final ValueSetter imageSetter;
  206. final RequestType type;
  207. final String api;
  208. final dynamic parameter;
  209. final bool isLoading;
  210. final bool isToken;
  211. const YSImageUploadView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
  212. required this.imageSetter, required this.successSetter}) : super(key: key);
  213. @override
  214. YSImageUploadViewState createState() => YSImageUploadViewState();
  215. }
  216. class YSImageUploadViewState extends State<YSImageUploadView> {
  217. double _rota1 = 0.0;
  218. double _rota2 = 0.0;
  219. bool _isError = false;
  220. @override
  221. void initState() {
  222. Future.delayed(const Duration(seconds: 0)).then((value) async{
  223. Map dict = await _getData();
  224. if(dict.isNotEmpty){
  225. widget.successSetter(dict);
  226. }
  227. });
  228. super.initState();
  229. }
  230. _getData() async{
  231. String url = '$base${widget.api}';
  232. SharedPreferences prefs = await SharedPreferences.getInstance();
  233. String token = prefs.getString('token')??'';
  234. Map<String, dynamic> httpHeaders = {
  235. 'Accept': 'application/json,*/*',
  236. 'Content-Type': 'application/json',
  237. if(widget.isToken==true)'Authorization': 'Bearer $token'
  238. };
  239. try {
  240. LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
  241. // LogUtil.d('请求网址:$url\n加密参数:$secret');
  242. Response response;
  243. if(widget.type==RequestType.put){
  244. response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  245. }else if(widget.type==RequestType.post){
  246. response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: 100000,headers: httpHeaders),
  247. onReceiveProgress: (int1,int2){
  248. // LogUtil.d('rota========$int1 $int2');
  249. if(int2==-1){
  250. _rota1 = 1;
  251. }else{
  252. _rota1 = int1/int2;
  253. }
  254. setState(() {});
  255. },
  256. onSendProgress: (int1,int2){
  257. _rota2 = int1/int2;
  258. setState(() {});
  259. widget.imageSetter(_rota2);
  260. });
  261. }else if(widget.type==RequestType.delete){
  262. response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  263. }else{
  264. response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
  265. }
  266. LogUtil.d('请求网址:$url\n请求结果:${response.data}');
  267. // return;
  268. Map dict = response.data;
  269. if(!mounted)return;
  270. Navigator.pop(context);
  271. if(dict['code']==200){
  272. return dict;
  273. }else if(dict['code']==401){
  274. ysFlutterToast('${dict['msg']??''}');
  275. if (!mounted) return;
  276. // Navigator.of(context).push(
  277. // CupertinoPageRoute(builder: (context){
  278. // return const YSLogin();
  279. // })
  280. // );
  281. prefs.remove('token');
  282. return {};
  283. }else{
  284. ysFlutterToast('${dict['msg']??''}');
  285. return {};
  286. }
  287. } catch (error) {
  288. if (!mounted) return;
  289. Navigator.pop(context);
  290. _isError = true;
  291. setState(() {});
  292. LogUtil.d('请求网址:$url\n网络错误:$error');
  293. return {};
  294. }
  295. }
  296. @override
  297. Widget build(BuildContext context) {
  298. return WillPopScope(
  299. onWillPop: () async{
  300. return false;
  301. },
  302. child: widget.isLoading==false?Container():Center(
  303. child: Container(
  304. height: hsp(150),
  305. width: hsp(150),
  306. decoration: const BoxDecoration(
  307. borderRadius: BorderRadius.all(Radius.circular(5)),
  308. color: Colors.black45,
  309. ),
  310. alignment: Alignment.center,
  311. child: Column(
  312. mainAxisSize: MainAxisSize.min,
  313. children: [
  314. SizedBox(
  315. width: 60,
  316. height: 60,
  317. child: _isError==true?const Icon(
  318. Icons.error_outline,size: 60,color: Colors.redAccent,
  319. ):_rota2==1&&_rota1==1?const Icon(
  320. Icons.check,size: 60,color: Colors.green,
  321. ):_rota2<1?CircularProgressIndicator(
  322. value: _rota2,
  323. color: Colors.lightBlueAccent,
  324. backgroundColor: Colors.white,
  325. strokeWidth: 5,
  326. ):const CircularProgressIndicator(
  327. color: Colors.lightBlueAccent,
  328. backgroundColor: Colors.white,
  329. strokeWidth: 5,
  330. ),
  331. ),
  332. Container(
  333. margin: EdgeInsets.only(top: hsp(15)),
  334. child: Text(_isError==true?'出错了':_rota2<1?'上传中':_rota1<1?'读取中':'完成',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
  335. )
  336. ],
  337. ),
  338. ),
  339. )
  340. );
  341. }
  342. }