Flutter dio獲取數據顯示到listview中

首先引入dio庫json

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");
  }
}

雖然只是作一個列表顯示,根本不用寫這麼多,不過以後若是完善功能能夠用到cookie

 

 

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(),
      ),
    );
  }
}
相關文章
相關標籤/搜索