api_response.dart 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. int _parseCode(dynamic value) {
  2. if (value is int) return value;
  3. if (value is String) return int.tryParse(value) ?? -1;
  4. if (value is num) return value.toInt();
  5. return -1;
  6. }
  7. /// 统一 API 响应包装
  8. /// 后端格式:{ "code": 0, "data": {...}, "message": "ok" }
  9. class ApiResponse<T> {
  10. final int code;
  11. final T? data;
  12. final String message;
  13. const ApiResponse({
  14. required this.code,
  15. this.data,
  16. required this.message,
  17. });
  18. bool get isSuccess => code == 0;
  19. factory ApiResponse.fromJson(
  20. Map<String, dynamic> json,
  21. T Function(Object? json)? fromJsonT,
  22. ) {
  23. return ApiResponse<T>(
  24. code: _parseCode(json['code']),
  25. data: json['data'] != null && fromJsonT != null
  26. ? fromJsonT(json['data'])
  27. : json['data'] as T?,
  28. message: json['message'] as String? ?? json['msg'] as String? ?? '',
  29. );
  30. }
  31. }
  32. /// API 异常
  33. class ApiException implements Exception {
  34. final int code;
  35. final String message;
  36. const ApiException({required this.code, required this.message});
  37. @override
  38. String toString() => 'ApiException($code): $message';
  39. }