标签:you tin gets creat cancel 间隔 adapter text 取消
首先引入dio庫
dio: 2.1.0
編寫dio工具类
import ‘dart:io‘; import ‘dart:math‘; import ‘package:cookie_jar/cookie_jar.dart‘; import ‘package:dio/dio.dart‘; import ‘package:flutter/services.dart‘; import ‘dart:convert‘; class HttpUtil { static HttpUtil instance; Dio dio; BaseOptions options; CancelToken cancelToken = new CancelToken(); //单例模式 static HttpUtil getInstance() { if (null == instance) { instance = new HttpUtil(); } else { return instance; } } /* * config it and create */ HttpUtil() { //BaseOptions、Options、RequestOptions 都可以配置参数,优先级别依次递增,且可以根据优先级别覆盖参数 options = new BaseOptions( //请求基地址,可以包含子路径 baseUrl: "http://47.100.106.80:8080/", //连接服务器超时时间,单位是毫秒. connectTimeout: 10000, //响应流上前后两次接受到数据的间隔,单位为毫秒。 receiveTimeout: 5000, //Http请求头. headers: { //do something // "version": "1.0.0" }, //请求的Content-Type,默认值是[ContentType.json]. 也可以用ContentType.parse("application/x-www-form-urlencoded") contentType: ContentType.json, //表示期望以那种格式(方式)接受响应数据。接受4种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`, responseType: ResponseType.plain, ); dio = new Dio(options); //跳过https验证 (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) { client.badCertificateCallback = (X509Certificate cert, String host, int port) { return true; }; }; //Cookie管理 dio.interceptors.add(CookieManager(CookieJar())); //添加拦截器 dio.interceptors .add(InterceptorsWrapper(onRequest: (RequestOptions options) { print("请求之前"); options.headers={ }; options.contentType=ContentType.parse("application/json"); return options; //continue }, onResponse: (Response response) { print("响应之前"); // Do something with response data return response; // continue }, onError: (DioError e) { print("错误之前"); // Do something with response error return e; //continue })); } /* * get请求 * url:请求地址 * data:请求参数 * options:请求配置 * cancelToken:取消标识 */ get(url, {params, options, cancelToken}) async { Response response; try { response = await dio.get(url, queryParameters: params, options: options, cancelToken: cancelToken); print(‘get success---------${response.data}‘); } on DioError catch (e) { print(‘get error---------$e‘); formatError(e); } return response.data; } /* * post请求 */ post(url, {params, options, cancelToken}) async { Options op = new Options(contentType: ContentType.parse("application/json")); Response response; try { response = await dio.post(url, queryParameters: params, options: op, cancelToken: cancelToken); print(‘post success---------${response.data}‘); } on DioError catch (e) { print(‘post error---------$e‘ + e.message); formatError(e); } return response.data; } /// 发送json postJson(url, Map<String, dynamic> queryParameters) async { Options op = new Options(contentType: ContentType.parse("application/json")); Response response; try { response = await dio.post(url, data: queryParameters, options: op, cancelToken: cancelToken); print(‘post success---------${response.data}‘); } on DioError catch (e) { print(‘post error---------$e‘ + e.message); formatError(e); } return response.data; } /* * 下载文件 */ downloadFile(urlPath, savePath) async { Response response; try { response = await dio.download(urlPath, savePath, onReceiveProgress: (int count, int total) { //进度 print("$count $total"); }); print(‘downloadFile success---------${response.data}‘); } on DioError catch (e) { print(‘downloadFile error---------$e‘); formatError(e); } return response.data; } /* * error统一处理 */ void formatError(DioError e) { if (e.type == DioErrorType.CONNECT_TIMEOUT) { // It occurs when url is opened timeout. print("连接超时"); } else if (e.type == DioErrorType.SEND_TIMEOUT) { // It occurs when url is sent timeout. print("请求超时"); } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) { //It occurs when receiving timeout print("响应超时"); } else if (e.type == DioErrorType.RESPONSE) { // When the server response, but with a incorrect status, such as 404, 503... print("出现异常"); } else if (e.type == DioErrorType.CANCEL) { // When the request is cancelled, dio will throw a error with this type. print("请求取消"); } else { //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null. print("未知错误"); } } /* * 取消请求 * 同一个cancel token 可以用于多个请求,当一个cancel token取消时,所有使用该cancel token的请求都会被取消。 * 所以参数可选 */ void cancelRequests(CancelToken token) { token.cancel("cancelled"); } }
雖然只是做一個列表顯示,根本不用寫這麼多,不過以後如果完善功能可以用到
import ‘dart:convert‘; import ‘package:dio/dio.dart‘; import ‘package:flutter/material.dart‘; import ‘package:flutter_dio/DAL/SqlfliteManager.dart‘; import ‘package:flutter_dio/list_bean_entity.dart‘; import ‘package:flutter_dio/HttpUtil.dart‘; class DioPage extends StatefulWidget { @override _DioPageState createState() => _DioPageState(); } class _DioPageState extends State<DioPage> { List<ListBeanData>_listData=[]; // 查詢全部數據 Future<Null>_getSymptom()async{ Map<String,String>paras={}; var data; data=await HttpUtil().get("hr/all"); var resoMap=json.decode(data.toString()); ListBeanEntity listBeanEntity=ListBeanEntity.fromJson(resoMap); _listData=listBeanEntity.data; setState(() { }); } @override void initState() { // TODO: implement initState super.initState(); _getSymptom(); } //构造listtile Widget _buildRow(int index) { return Padding( padding: EdgeInsets.all(20.0), child: Column( children: <Widget>[ Text( _listData[index].account, style: TextStyle(color: Colors.black87, fontSize: 20), ), Text( _listData[index].info, style: TextStyle(color: Colors.grey, fontSize: 18), ), RaisedButton( onPressed: (){ String id=_listData[index].id.toString(); }, child: Text("刪除"), ) ], ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("DiO網絡請求"), ), body: ListView.separated( itemCount: _listData.length, itemBuilder: (BuildContext context, int index) => _buildRow(index), //子项的分割线 separatorBuilder: (BuildContext context, int index) => Divider(), ), ); } }
标签:you tin gets creat cancel 间隔 adapter text 取消
原文地址:https://www.cnblogs.com/inthecloud/p/11889661.html