Flutter Dio调用api

import 'package:dio/dio.dart';
import '../constants/toast.dart';
import '../constants/localStorage.dart';

class HttpManage {
  Dio _dio;

  HttpManage() {
    _dio = Dio();
  }

  /// 通用的网络请求
  requestData({String path, RequestMethod method, Map data}) async {
    /*请求方式*/
    var methodName = '';
    switch (method) {
      case RequestMethod.post:
        methodName = 'post';
        break;
      case RequestMethod.get:
        methodName = 'get';
        break;
    }

    /*用户token*/
    var userToken = '';
    userToken = await LocalStorage.getPrefString(TOKEN);
    if (userToken != '') {
      userToken = 'Bearer ' + userToken;
    }
    print('token ==== $userToken');
    return await _dio.request(
      path,
      queryParameters: data,
      options: Options(
        method: methodName,
        headers: {
          'Authorization': userToken
        }
      )
    ).then((response) {
      if (response.data['success'] == true) {
//        Map result = Map.from(response.data['result']);
        return response.data['result'];
      } else {
        if (response.data['subCode'] != 'getTbkItemConvert.user.nobindingtaobao') {
          AppToast.show(
              msg: response.data['error']
          );
        }
        print('success == false :${response.data['error']}');
      }
      print('data:::::$data');
    }).catchError((error) {
      if (error is DioError) {
        print('$path.error:::::${error.response.data['error']}');
        throw((error.response.data['error']));
      }
    }).whenComplete(() {
      print('complete');
    });
  }

  /// 通用的登录请求
  requestLogin({String path, RequestMethod method, Map data}) async {
    /*请求方式*/
    var methodName = '';
    switch (method) {
      case RequestMethod.post:
        methodName = 'post';
        break;
      case RequestMethod.get:
        methodName = 'get';
        break;
    }
    return await _dio.request(
        path,
        queryParameters: data,
        options: Options(
          method: methodName,
        )
    ).then((response) {
      return response.data;
    }).catchError((error) {
      AppToast.show(
        msg: '登录失败~'
      );
      if (error is DioError) {
        throw(Exception(error.response.data['message']));
      }
    }).whenComplete(() {
      print('complete');
    });
  }

}

final httpManage = HttpManage();

enum RequestMethod {
  post,
  get
}

你可能感兴趣的:(Flutter Dio调用api)