flutter dio网络请求封装经过多次修改更新 呕心沥血而成的封装版本 返回future 加入token的版本

flutter dio网络请求封装经过多次修改更新 呕心沥血而成的封装版本 返回future

由于我们的flutter,虽然已经有了Dio的网络请求插件,但是还是不够简单明了,所以在此基础上我们进行了相应的封装,话不多说,直接上代码

可以对特定的code进行处理

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../main.dart';
import '../api/SpUtil.dart';

int errorRequestTimes = 0;
// ignore: non_constant_identifier_names
Future FutureDio(String methods, String api, Map<String, dynamic> obj) async {
  print(api);
  print(obj);
///注意:请求参数的数据类型是Map,数据结构类型是key为String,value可以是任意类型dynamic
///    example
//    FutureDio('post', Api.ListActivity,{"sid":"076003"} ).then((res){
//       print(res.data);
//     });

  ///接口错误类型
/*  每个接口都有可能返回下面错误:
  -1, "未知错误"
  51, "无权访问"
  109, "请重新登录"
  115,"频繁访问“
  128, "无效账户"
  129, "账户已冻结"
  130, "账户已注销"
  对404的处理*/

  /// 自定义Header
  Map<String, dynamic> httpHeaders = {
    'Accept': 'application/json,*/*',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ${SpUtil.preferences.getString('user_token')}'//同步的版本获取token Sputil的用法可以百度一下
  };

  var options = BaseOptions(
      sendTimeout:15000,
      connectTimeout: 60000,
      receiveTimeout: 60000,
      responseType: ResponseType.json,
      validateStatus: (status) {
        // 不使用http状态码判断状态,使用AdapterInterceptor来处理(适用于标准REST风格)
        return true;
      },
      headers: httpHeaders);
  Dio dio = new Dio(options);

  try {
    Response response;
    /// 判断请求的方式调用dio不同的请求api
    if (methods == "post") {
      response = await dio.post(api, data: obj);
    } else if (methods == 'get') {
      response = await dio.get(api, queryParameters: obj);
    } //注意get请求使用queryParameters接收参数,post请求使用data接收参数
    ///返回正常
    print(response.data);
    if (
    response.data['code'] == 0||
        response.data['code'] == 133||
        response.data['code'] == 11||
        response.data['code'] == 104||
        response.data['code'] == 56||
        response.data['code'] == 143||
        response.data['code'] == 132||
        response.data['code'] == 131||
        response.data['code'] == 43||
        response.data['code'] == 144||
        response.data['code'] == 56
    ) {
      return response; //返回请求结果
    }
    ///接口错误
    else if (response.data['code'] == -1) {
      Fluttertoast.showToast(
          msg: response.data['msg']??"未知错误",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print(response.data['msg']);
      print(response.data);
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/', (route) => false);
      });
    }
    ///无权访问
    else if (response.data['code'] == 51) {
      Fluttertoast.showToast(
          msg: '请重新登录!',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print('无权访问');
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/', (route) => false);
      });
    }
    ///token失效 请重新登录
    else if (response.data['code'] == 109) {
      Fluttertoast.showToast(
          msg: response.data['msg'] ?? "请重新登录",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print('request error');
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/login', (route) => false);
      });
    }

    ///无效账户
    else if (response.data['code'] == 128) {
      Fluttertoast.showToast(
          msg: response.data['msg'] ?? "无效账户",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print('无效账户');
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/', (route) => false);
      });
    }

    ///账户已冻结
    else if (response.data['code'] == 129) {
      Fluttertoast.showToast(
          msg: response.data['msg'] ?? "账户已冻结",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print('账户已冻结');
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/', (route) => false);
      });
    }

    ///账户已注销
    else if (response.data['code'] == 130) {
      Fluttertoast.showToast(
          msg: response.data['msg'] ?? "账户已注销",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
      print('账户已注销');
      Future.delayed(Duration(milliseconds: 800)).then((e) {
        Router.navigatorKey.currentState.pushNamedAndRemoveUntil('/', (route) => false);
      });
    }
    else {
 if(response.data['msg']!=null&&response.data['msg']!=""&&response.data['code']!=133){
        Fluttertoast.showToast(
            msg: response.data['msg'] ?? "未知错误",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.black38,
            textColor: Colors.white,
            fontSize: 16.0);
      }
    }
  } catch (e) {
    errorRequestTimes++;
    if(errorRequestTimes%7 == 0) {//7次错误请求提示一次,避免提示过于频繁
      Fluttertoast.showToast(
          msg: "连接超时",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 0,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }
}

代码示例

FutureDio('post', Api.ListActivity,{"code":"xx"} ).then((res){
    print(res.data);
  });
 FutureDio('get', Api.ListActivity,{"code":"xx"} ).then((res){
   print(res.data);
 });

这里的Api是另外写的接口文档 便于接口的维护

// api 接口
class Api {
  static const String BASE_URL = 'http://xx.xx.xx.xx';

  static const String AppRelogin = BASE_URL + '/auth/appRelogin'; //初始化 重新登录 app初始化时调用

  static const String GetSections = BASE_URL + '/config/getSectionsApp'; //板块
}

同步Sputil的代码

import 'package:shared_preferences/shared_preferences.dart';
class SpUtil{
  static SharedPreferences preferences;
  static Future getInstance() async{
    preferences = await SharedPreferences.getInstance();
    return true;
  }
}

//example
//SpUtil.preferences.getString('provinceName')
//SpUtil.preferences.setString('provinceCode', 'xxxx');

你可能感兴趣的:(flutter)