Dio的超简单封装,超好用

直接复制

import 'dart:convert';

import 'package:dio/dio.dart';

enum HttpMethod { post, get }

typedef ParseObject = dynamic Function(dynamic originMap);

extension ListExt on List {
  List parseObj(ParseObject covert) {
    return List.from(map(covert)).toList();
  }
}

extension ResultJsonExt on ResultJson? {
  bool get requestIsSuccess => this!=null && this!.success == true && this!.errors.isEmpty;
}

abstract class BaseModel {
  T fromJson(Map map);
}

class ResultJson {
  final bool success;
  final String errorMessage;
  final List errors;
  final dynamic data;

  ResultJson(
      {required this.success,
      required this.errorMessage,
      required this.errors,
      required this.data});

  factory ResultJson.fromJson(Map map) {
    return ResultJson(
        success: map['success'],
        errorMessage: map['errorMessage'] ?? '',
        errors: map['errors'] ?? [],
        data: map['data']);
  }

  //打印
  void printDataJson() {
    print(jsonEncode(data));
  }

  //转数组
  List parseList() {
    return data as List;
  }

  List dataCovertToList(ParseObject covert) {
    return parseList().parseObj(covert).toList();
  }

  @override
  String toString() {
    return '==========================================\n是否成功:${success ? '成功' : '失败'} data类型:${data.runtimeType} \n错误消息:$errorMessage\n错误列表:$errors\n数据:$data\n==========================================';
  }
}

abstract class BaseApi {
  static String host = 'http://192.168.199.79:8888';

  final String url;
  final HttpMethod httpMethod;
  final Map params = {};

  BaseApi(this.url, {this.httpMethod = HttpMethod.get});

  Future request() async {
    final response = await Dio().request(host + url,
        options: Options(method: methed),
        queryParameters: params,
        data: params);
    if (response.statusCode == 200) {
      final data = response.data;
      return ResultJson.fromJson(data);
    }
    return null;
  }

  //请求方法,
  String get methed => getMethod();

  String getMethod() {
    switch (httpMethod) {
      case HttpMethod.get:
        return 'GET';
      default:
        return "POST";
    }
  }
}


使用


import 'package:girlmerry_zhubo/api/base.dart';

class RoomApi extends BaseApi {
  RoomApi() : super('/app/api/room/list');
}


class StartLiveApi extends BaseApi {
  StartLiveApi(): super('/app/api/room/start',httpMethod: HttpMethod.post);
  set setId(int roomId) => params['id'] = '$roomId';
}

你可能感兴趣的:(Dio的超简单封装,超好用)