Commit 8d581dd25cde5752de7ad3698ed85e1455d9e9bd

Authored by 吴启风
1 parent 83beb925

feat: 给字段手写 JsonKey 的 fromJson/toJson,避免build_runner (json_serializable)无法为泛型字段 …

…T data 自动生成代码而报错(Could not generate fromJson code for data because of type T)
lib/common/request/api_response/api_response_entity.dart
1 import 'dart:convert'; 1 import 'dart:convert';
2 2
3 -import 'package:json_annotation/json_annotation.dart';  
4 -  
5 -import 'api_response_entity.g.dart';  
6 -  
7 -@JsonSerializable(genericArgumentFactories: true) 3 +// No json_serializable here; keep a lightweight manual model to mimic old behavior
  4 +import 'package:wow_english/generated/json/base/json_convert_content.dart';
8 class ApiResponse<T> { 5 class ApiResponse<T> {
9 int? code; 6 int? code;
10 String? msg; 7 String? msg;
@@ -12,9 +9,21 @@ class ApiResponse&lt;T&gt; { @@ -12,9 +9,21 @@ class ApiResponse&lt;T&gt; {
12 9
13 ApiResponse(); 10 ApiResponse();
14 11
15 - factory ApiResponse.fromJson(Map<String, dynamic> json) => $ApiResponseFromJson<T>(json); 12 + factory ApiResponse.fromJson(Map<String, dynamic> json) {
  13 + final resp = ApiResponse<T>();
  14 + resp.code = jsonConvert.convert<int>(json['code']);
  15 + resp.msg = jsonConvert.convert<String>(json['msg']);
  16 + if (json['data'] != null) {
  17 + resp.data = JsonConvert.fromJsonAsT<T>(json['data']);
  18 + }
  19 + return resp;
  20 + }
16 21
17 - Map<String, dynamic> toJson() => $ApiResponseToJson(this); 22 + Map<String, dynamic> toJson() => <String, dynamic>{
  23 + 'code': code,
  24 + 'msg': msg,
  25 + 'data': data,
  26 + };
18 27
19 @override 28 @override
20 String toString() { 29 String toString() {
lib/common/request/api_response/api_response_entity.g.dart deleted
1 -import 'package:flutter/foundation.dart';  
2 -  
3 -import '../../../generated/json/base/json_convert_content.dart';  
4 -import 'api_response_entity.dart';  
5 -  
6 -ApiResponse<T> $ApiResponseFromJson<T>(Map<String, dynamic> json) {  
7 - final ApiResponse<T> apiResponseEntity = ApiResponse<T>();  
8 - final int? code = jsonConvert.convert<int>(json['code']);  
9 - if (code != null) {  
10 - apiResponseEntity.code = code;  
11 - }  
12 - final String? msg = jsonConvert.convert<String>(json['msg']);  
13 - if (msg != null) {  
14 - apiResponseEntity.msg = msg;  
15 - }  
16 - String type = T.toString();  
17 - T? data;  
18 - if (kDebugMode) {  
19 - print("ApiResponse<T> T-type:$type, data-type:${json['data'].runtimeType}");  
20 - }  
21 - if (json['data'] != null) {  
22 - data = JsonConvert.fromJsonAsT(json['data']);  
23 - }  
24 - if (data != null) {  
25 - apiResponseEntity.data = data;  
26 - }  
27 - return apiResponseEntity;  
28 -}  
29 -  
30 -Map<String, dynamic> $ApiResponseToJson(ApiResponse entity) {  
31 - final Map<String, dynamic> data = <String, dynamic>{};  
32 - data['code'] = entity.code;  
33 - data['msg'] = entity.msg;  
34 - data['data'] = entity.data;  
35 - return data;  
36 -}