31. dio二次封装&接口统一管理及数据模型构建

配置权限

<!-- 打包后的网络请求配置 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Dio二次封装拦截器配置

创建 http.dart 文件

import 'package:dio/dio.dart';

class MyHttp {
  late Dio _dio;

  MyHttp() {
    BaseOptions options = BaseOptions(
      baseUrl: 'baseURL',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 3),
    );
    _dio = Dio(options);
  }

  Future<T> get<T>(String path, {Map<String, dynamic> ?queryParameters, String ?token}) async {
    try {
      Response response = await _dio.get(
        path,
        queryParameters: queryParameters,
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );
      return response.data;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<T> post<T>(String path, {Map<String, dynamic> ?data, String ?token}) async {
    try {
      Response response = await _dio.post(
        path,
        data: data,
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );
      return response.data;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<T> upload<T>(String path, String filePath, {String ?token}) async {
    try {
      FormData formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(filePath),
      });
      Response response = await _dio.post(
        path,
        data: formData,
        options: Options(
          headers: {'Authorization': 'Bearer $token'},
          contentType: 'multipart/form-data',
        ),
      );
      return response.data;
    } catch (e) {
      throw e;
    }
  }

  dynamic _handleError(dynamic e) {
    if (e is DioException) {
      if (e.response != null) {
        /* 请求成功,但服务器返回错误状态码 */
        throw BadRequestException(e.response!.data['message']);
      } else {
        /* 请求失败,网络异常等 */
        throw BadRequestException("请求失败,网络异常");
      }
    } else {
      throw e;
    }
  }


}

class BadRequestException implements Exception {
  final String message;

  BadRequestException(this.message);

  @override
  String toString() {
    return message;
  }
}

接口统一管理

创建 api / login.dart 文件名根据项目和业务名称自定义

import '../utils/HttpsClient.dart';
​
class Test {
  late HttpsClient httpsClient;
  Test(){
    httpsClient = HttpsClient();
import '../http.dart';

MyHttp http = MyHttp();
class LoginApi {
  static Future login(Map<String,dynamic> data)async{
    try {
      var response = await http.post("/login",data:data);
      return  response;
    } catch (e) {
      throw e;
    }
  }
}

使用

import 'package:get/get.dart';
import '/api/user.dart';
​
class LoginController extends GetxController {
handelLogin(){
     var response =await LoginApi.login({
          "name":"admin"
     });
}

JsonModel构建数据模型

用于声明接口中字段的类型,思想同 TS 中的 interdace;

创建

方式一: 借助第三方网站 https://autocode.icu/jsontodart

方式二: 使用 get_cli 命令行生成, 声明的类名推荐改为 xxxModel

get generate model on  modelsFile from "接口地址的URL" 

此时会在 lib 目录中新建 modelsFile 文件夹

使用

TestModel data = TestModel.fromJson(json.decode(JSONDATA)) /* json 字符串转 map*/
print(data.key) /* key的value */

赋值

RxList listData = [].obs;
listData.value = data.response; /* 此时赋值会报错,悬停会有类型提示,将提示类型放到 RxList 的泛型中 */
/* 需要将 RxList 传入泛型 */
RxList<TestModelType> listData = <TestModelType>[].obs;
listData.value = data!;
/* 设置数据模型的默认值 */
Rx<TestModelType> data = TestModelType().obs;
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇