封装网络请求, 我使用了 Dio 库。

    HttpUtil.dart

    1. import 'package:dio/dio.dart';
    2. class HttpUtil {
    3. static HttpUtil instance;
    4. Dio dio;
    5. BaseOptions options;
    6. String baseUrl = "https://5d5a45132257cc001496241b.mockapi.io/api/";
    7. static HttpUtil getInstance() {
    8. print('getInstance');
    9. if (instance == null) {
    10. instance = new HttpUtil();
    11. }
    12. return instance;
    13. }
    14. HttpUtil() {
    15. options = BaseOptions(
    16. // 请求基地址,可以包含子路径,如: "//www.google.com/api/".
    17. baseUrl: baseUrl,
    18. //连接服务器超时时间,单位是毫秒.
    19. connectTimeout: 10000,
    20. /// 响应流上前后两次接受到数据的间隔,单位为毫秒。如果两次间隔超过[receiveTimeout],
    21. /// [Dio] 将会抛出一个[DioErrorType.RECEIVE_TIMEOUT]的异常.
    22. /// 注意: 这并不是接收数据的总时限.
    23. receiveTimeout: 3000,
    24. headers: {},
    25. );
    26. dio = new Dio(options);
    27. }
    28. resolve(List api, {data, options, cancelToken}) async {
    29. switch (api[1]) {
    30. case 'get':
    31. return await this.get(
    32. api[0],
    33. data: data,
    34. options: options,
    35. cancelToken: cancelToken
    36. );
    37. break;
    38. case 'post':
    39. return await this.post(
    40. api[0],
    41. data: data,
    42. options: options,
    43. cancelToken: cancelToken
    44. );
    45. break;
    46. default:
    47. break;
    48. }
    49. }
    50. get(url, {data, options, cancelToken}) async {
    51. print('get请求启动! url:$url ,body: $data');
    52. Response response;
    53. try {
    54. response = await dio.get(
    55. url,
    56. queryParameters: data,
    57. cancelToken: cancelToken,
    58. );
    59. print('get请求成功! response.data:${response.data}');
    60. } on DioError catch (e) {
    61. if (CancelToken.isCancel(e)) {
    62. print('get请求取消! ' + e.message);
    63. }
    64. print('get请求发生错误:$e');
    65. }
    66. return response.data;
    67. }
    68. post(url, {data, options, cancelToken}) async {
    69. print('post请求启动! url:$url ,body: $data');
    70. Response response;
    71. try {
    72. response = await dio.post(
    73. url,
    74. data: data,
    75. cancelToken: cancelToken,
    76. );
    77. print('post请求成功! response.data:${response.data}');
    78. } on DioError catch (e) {
    79. if (CancelToken.isCancel(e)) {
    80. print('post请求取消! ' + e.message);
    81. }
    82. print('post请求发生错误:$e');
    83. }
    84. return response.data;
    85. }
    86. }

    Api.dart

    1. class Api {
    2. static List USER_LIST = ['user', 'get'];
    3. }

    使用方式:

    1. Future getData() async {
    2. var data = {'pageIndex': 1, 'pageSize': 10};
    3. var response = await HttpUtil().resolve(Api.USER_LIST, data: data);
    4. print(response);
    5. print(response is List); // true
    6. print(response[0] is Map); // true
    7. }

    可以看到, 返回的 json 数据自动转化为了 List 或 Map 格式的数据。