123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- import 'dart:convert';
- import 'package:dio/dio.dart';
- import 'package:flutter/cupertino.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter_tzh/login/YSLogin.dart';
- import 'package:fluttertoast/fluttertoast.dart';
- // import 'package:fluttertoast/fluttertoast.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'YSTools.dart';
- //http://192.168.1.22:8888
- //http://114.115.251.233:30034
- String base = 'http://114.115.251.233:30034/api';
- int outTime = 50000;
- enum RequestType{
- put,
- delete,
- get,
- post
- }
- class YSNetWork{
- int outTime = 20000;
- static ysRequestHttp(BuildContext context,{required RequestType type,required String api,required dynamic parameter,bool isLoading = false,bool isToken = true,required ValueSetter successSetter}) async{
- if(isLoading==false){
- int outTime = 20000;
- String url = '$base$api';
- SharedPreferences prefs = await SharedPreferences.getInstance();
- String token = prefs.getString('token')??'';
- // LogUtil.d('请求token:$token');
- Map<String, dynamic> httpHeaders = {
- 'Accept': 'application/json,*/*',
- 'Content-Type': 'application/json',
- if(isToken==true)'Authorization': 'Bearer $token'
- };
- LogUtil.d('请求头 $httpHeaders');
- try {
- LogUtil.d('请求网址:$url\n请求参数:$parameter');
- Response response;
- if(type==RequestType.put){
- response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else if(type==RequestType.post){
- response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else if(type==RequestType.delete){
- response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else{
- response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }
- // LogUtil.d('请求网址:$url\n请求结果:${response.data}');
- Map dict = response.data;
- LogUtil.d('请求网址:$url\n请求结果:$dict');
- if(dict['code']==200){
- successSetter(dict);
- }else if(dict['code']==401){
- ysFlutterToast('${dict['msg']??''}');
- prefs.remove('token');
- // ignore: use_build_context_synchronously
- Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
- return const YSLogin();
- }), (route) => false);
- }else{
- ysFlutterToast('${dict['msg']??''}');
- }
- } catch (error) {
- LogUtil.d('请求网址:$url\n网络错误:$error');
- }
- }else{
- ysShowCenterAlertView(context, YSNetWorkView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){},successSetter: (value){
- successSetter(value);
- },),isTrans: true);
- }
- }
- static ysRequestHttp2(BuildContext context,{required RequestType type,required String api,required dynamic parameter,bool isLoading = false,bool isToken = true,required
- ValueSetter imageSetter,required ValueSetter successSetter}) {
- FocusScope.of(context).unfocus();
- ysShowCenterAlertView(context, YSImageUploadView(type: type, api: api,parameter: parameter,isLoading: isLoading,isToken: isToken,imageSetter: (value){
- imageSetter(value);
- },successSetter: (value){
- successSetter(value);
- }),isTrans: true);
- }
- }
- void ysFlutterToast(String msg,{bool isCenter = false}){
- Fluttertoast.showToast(
- msg: msg,
- gravity: isCenter?ToastGravity.CENTER:ToastGravity.BOTTOM,
- textColor: Colors.white,
- backgroundColor: Colors.black87,
- timeInSecForIosWeb: 2,
- );
- }
- class YSNetWorkView extends StatefulWidget {
- final ValueSetter successSetter;
- final ValueSetter imageSetter;
- final RequestType type;
- final String api;
- final dynamic parameter;
- final bool isLoading;
- final bool isToken;
- final bool isImage;
- const YSNetWorkView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
- required this.imageSetter,this.isImage = false, required this.successSetter}) : super(key: key);
- @override
- YSNetWorkViewState createState() => YSNetWorkViewState();
- }
- class YSNetWorkViewState extends State<YSNetWorkView> {
- bool _isError = false;
- @override
- void initState() {
- Future.delayed(const Duration(seconds: 0)).then((value) async{
- Map dict = await _getData();
- if(dict.isNotEmpty){
- widget.successSetter(dict);
- }
- });
- super.initState();
- }
- _getData() async{
- String url = '$base${widget.api}';
- SharedPreferences prefs = await SharedPreferences.getInstance();
- String token = prefs.getString('token')??'';
- Map<String, dynamic> httpHeaders = {
- 'Accept': 'application/json,*/*',
- 'Content-Type': 'application/json',
- if(widget.isToken==true)'Authorization': 'Bearer $token'
- };
- try {
- LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
- Response response;
- if(widget.type==RequestType.put){
- response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else if(widget.type==RequestType.post){
- response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else if(widget.type==RequestType.delete){
- response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else{
- response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }
- LogUtil.d('请求网址:$url\n请求结果:${response.data}');
- Map dict = response.data;
- if(!mounted)return;
- Navigator.pop(context);
- if(dict['code']==200){
- return dict;
- }else if(dict['code']==401){
- ysFlutterToast('${dict['msg']??''}');
- if (!mounted) return;
- Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
- return const YSLogin();
- }), (route) => false);
- prefs.remove('token');
- return {};
- }else{
- ysFlutterToast('${dict['msg']??''}');
- return {};
- }
- } catch (error) {
- if (!mounted) return;
- Navigator.pop(context);
- _isError = true;
- setState(() {});
- LogUtil.d('请求网址:$url\n网络错误:$error');
- return {};
- }
- }
- @override
- Widget build(BuildContext context) {
- return WillPopScope(
- onWillPop: () async{
- return false;
- },
- child: widget.isLoading==false?Container():Center(
- child: Container(
- height: hsp(150),
- width: hsp(150),
- decoration: const BoxDecoration(
- borderRadius: BorderRadius.all(Radius.circular(5)),
- color: Colors.black45,
- ),
- alignment: Alignment.center,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SizedBox(
- width: 60,
- height: 60,
- child: _isError==true?const Icon(
- Icons.error_outline,size: 60,color: Colors.redAccent,
- ):CupertinoActivityIndicator(
- radius: hsp(20),
- color: Colors.white,
- ),
- ),
- Container(
- margin: EdgeInsets.only(top: hsp(15)),
- child: Text(_isError==true?'出错了':'请求中',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
- )
- ],
- ),
- ),
- ),
- );
- }
- }
- class YSImageUploadView extends StatefulWidget {
- final ValueSetter successSetter;
- final ValueSetter imageSetter;
- final RequestType type;
- final String api;
- final dynamic parameter;
- final bool isLoading;
- final bool isToken;
- const YSImageUploadView({Key? key, required this.type, required this.api, this.parameter, this.isLoading = false, this.isToken = true,
- required this.imageSetter, required this.successSetter}) : super(key: key);
- @override
- YSImageUploadViewState createState() => YSImageUploadViewState();
- }
- class YSImageUploadViewState extends State<YSImageUploadView> {
- double _rota1 = 0.0;
- double _rota2 = 0.0;
- bool _isError = false;
- @override
- void initState() {
- Future.delayed(const Duration(seconds: 0)).then((value) async{
- Map dict = await _getData();
- if(dict.isNotEmpty){
- widget.successSetter(dict);
- }
- });
- super.initState();
- }
- _getData() async{
- String url = '$base${widget.api}';
- SharedPreferences prefs = await SharedPreferences.getInstance();
- String token = prefs.getString('token')??'';
- Map<String, dynamic> httpHeaders = {
- 'Accept': 'application/json,*/*',
- 'Content-Type': 'application/json',
- if(widget.isToken==true)'Authorization': 'Bearer $token'
- };
- try {
- LogUtil.d('请求网址:$url\n请求参数:${widget.parameter}');
- // LogUtil.d('请求网址:$url\n加密参数:$secret');
- Response response;
- if(widget.type==RequestType.put){
- response = await Dio().put(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else if(widget.type==RequestType.post){
- response = await Dio().post(url,data: widget.parameter,options: Options(receiveTimeout: 100000,headers: httpHeaders),
- onReceiveProgress: (int1,int2){
- // LogUtil.d('rota========$int1 $int2');
- if(int2==-1){
- _rota1 = 1;
- }else{
- _rota1 = int1/int2;
- }
- setState(() {});
- },
- onSendProgress: (int1,int2){
- _rota2 = int1/int2;
- setState(() {});
- widget.imageSetter(_rota2);
- });
- }else if(widget.type==RequestType.delete){
- response = await Dio().delete(url,data: widget.parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }else{
- response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(widget.parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
- }
- LogUtil.d('请求网址:$url\n请求结果:${response.data}');
- // return;
- Map dict = response.data;
- if(!mounted)return;
- Navigator.pop(context);
- if(dict['code']==200){
- return dict;
- }else if(dict['code']==401){
- ysFlutterToast('${dict['msg']??''}');
- if (!mounted) return;
- // Navigator.of(context).push(
- // CupertinoPageRoute(builder: (context){
- // return const YSLogin();
- // })
- // );
- prefs.remove('token');
- return {};
- }else{
- ysFlutterToast('${dict['msg']??''}');
- return {};
- }
- } catch (error) {
- if (!mounted) return;
- Navigator.pop(context);
- _isError = true;
- setState(() {});
- LogUtil.d('请求网址:$url\n网络错误:$error');
- return {};
- }
- }
- @override
- Widget build(BuildContext context) {
- return WillPopScope(
- onWillPop: () async{
- return false;
- },
- child: widget.isLoading==false?Container():Center(
- child: Container(
- height: hsp(150),
- width: hsp(150),
- decoration: const BoxDecoration(
- borderRadius: BorderRadius.all(Radius.circular(5)),
- color: Colors.black45,
- ),
- alignment: Alignment.center,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SizedBox(
- width: 60,
- height: 60,
- child: _isError==true?const Icon(
- Icons.error_outline,size: 60,color: Colors.redAccent,
- ):_rota2==1&&_rota1==1?const Icon(
- Icons.check,size: 60,color: Colors.green,
- ):_rota2<1?CircularProgressIndicator(
- value: _rota2,
- color: Colors.lightBlueAccent,
- backgroundColor: Colors.white,
- strokeWidth: 5,
- ):const CircularProgressIndicator(
- color: Colors.lightBlueAccent,
- backgroundColor: Colors.white,
- strokeWidth: 5,
- ),
- ),
- Container(
- margin: EdgeInsets.only(top: hsp(15)),
- child: Text(_isError==true?'出错了':_rota2<1?'上传中':_rota1<1?'读取中':'完成',style: TextStyle(fontSize: zsp(16),color: Colors.white,decoration: TextDecoration.none),),
- )
- ],
- ),
- ),
- )
- );
- }
- }
|