fluter http请求

59 阅读1分钟

使用 http

http: ^0.13.5

数据模型 使用泛型 这里的BaseResponse 是code data mag 后面只需向data 提供具体的自己类型

```

import 'package:json_annotation/json_annotation.dart';

part 'BaseResponse.g.dart';

@JsonSerializable(genericArgumentFactories: true) class BaseResponse { final int code; final String msg; final T data;

BaseResponse({ required this.code, required this.msg, required this.data, });

factory BaseResponse.fromJson( Map<String, dynamic> json, T Function(Object? json) fromJsonT, ) => _$BaseResponseFromJson(json, fromJsonT);

Map<String, dynamic> toJson(Object Function(T value) toJsonT) => _$BaseResponseToJson(this, toJsonT); }

    
    
    
 自动化数据模型
    

json_annotation

    ```
json_serializable

自动化数据模型命令

flutter pub run build_runner build

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/BaseResponse.dart';

typedef RequestInterceptor = Future<http.BaseRequest> Function(http.BaseRequest request);
typedef ResponseInterceptor = Future<http.Response> Function(http.Response response);

class HttpService {
 static const String _baseUrl = '自己项目的baseUrl';

 static RequestInterceptor? requestInterceptor;
 static ResponseInterceptor? responseInterceptor;

 static void setInterceptors({
   RequestInterceptor? onRequest,
   ResponseInterceptor? onResponse,
 }) {
   requestInterceptor = onRequest;
   responseInterceptor = onResponse;
 }

 // 👇 支持直接返回 BaseResponse<T>
 static Future<BaseResponse<T>> getData<T>(
     String path, {
       Map<String, String>? headers,
       Map<String, dynamic>? queryParams,
       required T Function(Object? json) fromJsonT,
     }) {
   return get<BaseResponse<T>>(
     path,
     headers: headers,
     queryParams: queryParams,
     fromJson: (json) => BaseResponse<T>.fromJson(json, fromJsonT),
   );
 }

 static Future<T> get<T>(
     String path, {
       Map<String, String>? headers,
       Map<String, dynamic>? queryParams,
       required T Function(Map<String, dynamic>) fromJson,
     }) async {
   final uri = Uri.parse('$_baseUrl$path').replace(queryParameters: queryParams?.map((key, value) => MapEntry(key, value.toString())));
   final request = http.Request('GET', uri);
   if (headers != null) {
     request.headers.addAll(headers);
   }
   return _send(request, fromJson);
 }

 static Future<T> post<T>(
     String path, {
       Map<String, String>? headers,
       dynamic body,
       required T Function(Map<String, dynamic>) fromJson,
     }) async {
   final uri = Uri.parse('$_baseUrl$path');

   final request = http.Request('POST', uri);
   request.headers.addAll({
     'Content-Type': 'application/json',
     ...?headers,
   });

   if (body != null) {
     request.body = jsonEncode(body);
   }

   return _send(request, fromJson);
 }

 static Future<T> _send<T>(
     http.BaseRequest request,
     T Function(Map<String, dynamic>) fromJson,
     ) async {
   if (requestInterceptor != null) {
     request = await requestInterceptor!(request);
   }

   final streamedResponse = await request.send();
   final response = await http.Response.fromStream(streamedResponse);

   if (responseInterceptor != null) {
     return fromJson(jsonDecode((await responseInterceptor!(response)).body));
   }

   final int statusCode = response.statusCode;
   final body = response.body.isNotEmpty ? jsonDecode(response.body) : {};

   if (statusCode >= 200 && statusCode < 300) {
     return fromJson(body);
   } else {
     throw Exception('请求失败: $statusCode - ${body['message'] ?? '未知错误'}');
   }
 }
}