Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DioForNative set transformer invalid #2350

Closed
pangli opened this issue Jan 6, 2025 · 1 comment
Closed

DioForNative set transformer invalid #2350

pangli opened this issue Jan 6, 2025 · 1 comment

Comments

@pangli
Copy link

pangli commented Jan 6, 2025

Package

dio

Version

5.7.0

Operating-System

Android

Adapter

Default Dio

Output of flutter doctor -v

PS C:\Users\hlzf\Desktop> flutter doctor -v
[✓] Flutter (Channel stable, 3.27.1, on Microsoft Windows [版本 10.0.26100.2605], locale zh-CN)
    • Flutter version 3.27.1 on channel stable at E:\FlutterSdk
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 17025dd882 (3 weeks ago), 2024-12-17 03:23:09 +0900
    • Engine revision cb4b5fff73
    • Dart version 3.6.0
    • DevTools version 2.40.2

[✓] Windows Version (Installed version of Windows is version 10 or higher)

[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
    • Android SDK at E:\AndroidSdk
    • Platform android-35, build-tools 35.0.0
    • Java binary at: E:\AndroidStudio\jbr\bin\java
    • Java version OpenJDK Runtime Environment (build 21.0.3+-12282718-b509.11)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[✗] Visual Studio - develop Windows apps
    ✗ Visual Studio not installed; this is necessary to develop Windows apps.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components

[✓] Android Studio (version 2024.2)
    • Android Studio at E:\AndroidStudio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 21.0.3+-12282718-b509.11)

[✓] IntelliJ IDEA Ultimate Edition (version 2023.2)
    • IntelliJ at C:\Program Files\idea\IntelliJ IDEA 2023.2.5
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] Connected device (4 available)
    • PJY110 (mobile)   • AMYTVGBYUCFUPROV • android-arm64  • Android 14 (API 34)
    • Windows (desktop) • windows          • windows-x64    • Microsoft Windows [版本 10.0.26100.2605]
    • Chrome (web)      • chrome           • web-javascript • Google Chrome 130.0.6723.92
    • Edge (web)        • edge             • web-javascript • Microsoft Edge 131.0.2903.112

[✓] Network resources
    • All expected network resources are available.

Dart Version

3.6.0

Steps to Reproduce

import 'dart:convert';

import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';

export 'package:dio/dio.dart';

/// 
Map<String, dynamic> _parseAndDecode(String response) {
  return jsonDecode(response) as Map<String, dynamic>;
}

Future<Map<String, dynamic>> parseJson(String text) {
  return compute(_parseAndDecode, text);
}

abstract class BaseHttp extends DioForNative {
  /// 无效
  @override
  Transformer get transformer => DefaultTransformer()..jsonDecodeCallback = parseJson;
  BaseHttp() {
    /// 无效
    // transformer = DefaultTransformer()..jsonDecodeCallback = parseJson;
    interceptors.add(ConfigInterceptor());
    init();
  }

  void init();
}

/// 添加常用Config
class ConfigInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options
      ..connectTimeout = const Duration(seconds: 60)
      ..sendTimeout = const Duration(seconds: 60)
      ..receiveTimeout = const Duration(seconds: 60);
    super.onRequest(options, handler);
  }
}

/// 子类需要重写
abstract class BaseResponseData {
  int code = 0;
  String message = '';
  dynamic data;

  bool get success;

  Headers? headers;

  // BaseResponseData({required this.code, required this.message, this.result});

  @override
  String toString() {
    return 'BaseRespData{code: $code, message: $message, data: $data}';
  }
}

/// 接口的code没有返回为true的异常
class NotSuccessException implements Exception {
  String message = '';

  NotSuccessException.fromRespData(BaseResponseData respData) {
    message = respData.message;
  }

  @override
  String toString() {
    return 'NotExpectedException{respData: $message}';
  }
}

/// 用于未登录等权限不够,需要跳转授权页面
class UnAuthorizedException implements Exception {
  const UnAuthorizedException();

  @override
  String toString() => 'UnAuthorizedException';
}
import 'dart:convert';

import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../../base/net/base_net.dart';
import '../../base/util/platform_utils.dart';

const isDebug = true;
final KpHttp kpHttp = KpHttp();

class KpHttp extends BaseHttp {
  @override
  void init() {
    options.baseUrl = 'https://refs/heads/main/';
    interceptors
      ..add(HeaderInterceptor())
      ..add(ApiInterceptor())
      ..add(PrettyDioLogger(
          requestHeader: isDebug,
          requestBody: isDebug,
          responseHeader: isDebug));
  }
}

class HeaderInterceptor extends InterceptorsWrapper {
  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    var versionCode = await PlatformUtils.getBuildNum();
    options
      ..headers['User-Identity'] = "SYS/Android;$versionCode"
      ..headers['platform'] = Platform.operatingSystem;
    super.onRequest(options, handler);
  }
}

class ApiInterceptor extends InterceptorsWrapper {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    ResponseData respData =
        //有效
        // ResponseData.fromJson(response.headers, jsonDecode(response.data));
        ResponseData.fromJson(response.headers, response.data);
    if (respData.success) {
      response.data = respData.data;
      return handler.next(response);
    } else {
      if (respData.code == 1001 || respData.code == 1000) {
        throw const UnAuthorizedException(); // 需要登录
      } else {
        throw NotSuccessException.fromRespData(respData);
      }
    }
  }
}

class ResponseData extends BaseResponseData {
  @override
  bool get success => 0 == code;

  ResponseData.fromJson(
    Headers? headers,
    Map<String, dynamic> json,
  ) {
    this.headers = headers;
    code = json['code'];
    message = json['message'];
    data = json['data'];
  }
}
var response = await kpHttp.get('order_detail_data.json');
HomeTopBean homeTopEntity = HomeTopBean.fromJson(response.data.map);
debugPrint('测试数据——>$homeTopEntity');

Expected Result

╔╣ Response ║ GET ║ Status: 200 OK ║ Time: 1551 ms
║ https://order_detail_data.json
╚══════════════════════════════════════════════════════════════════════════════════════════╝
╔ Headers
╟ x-timer: [S1736158214.001342,VS0,VE269]
╟ x-fastly-request-id: [ceb7ec13777e655cf609730d34e9d722c9c0f587]
╟ date: [Mon, 06 Jan 2025 10:10:14 GMT]
╟ content-encoding: [gzip]
╟ vary: [Authorization,Accept-Encoding,Origin]
╟ x-served-by: [cache-mrs10550-MRS]
╟ cross-origin-resource-policy: [cross-origin]
╟ x-github-request-id: [1D6F:4E53C:ABE2F83:B313DA6:677BAC05]
╟ accept-ranges: [bytes]
╟ content-length: [397]
╟ etag: [W/"191b764e329eaa702a54fac2d48e608b0598b60e7e21c85c6185cb57ef1e93b1"]
╟ x-frame-options: [deny]
╟ source-age: [0]
╟ content-security-policy: [default-src 'none'; style-src 'unsafe-inline'; sandbox]
╟ x-cache-hits: [0]
╟ connection: [keep-alive]
╟ cache-control: [max-age=300]
╟ access-control-allow-origin: [*]
╟ strict-transport-security: [max-age=31536000]
╟ content-type: [text/plain; charset=utf-8]
╟ x-xss-protection: [1; mode=block]
╟ via: [1.1 varnish]
╟ x-content-type-options: [nosniff]
╟ x-cache: [MISS]
╟ expires: [Mon, 06 Jan 2025 10:15:14 GMT]
╚══════════════════════════════════════════════════════════════════════════════════════════╝
╔ Body

║ {
║ "order_id": "14454645664",
║ "serial_id": "345623234353464",
║ "create_time": "2021.03.11 12:00:00",
║ "payment_time": "2021.03.11 12:01:00",
║ "delivery_time": "2021.03.11 12:02:00",
║ "state": 4,
║ "currency": "$",
║ "total": 157840.25,
║ "tips": 20,
║ "product": 157820.25,
║ "products": [
║ {
║ "product_id": "id_0001_0001",
║ "product_name": "PUBG Mobile id_0001_0001",
║ "product_price": 199.99,
║ "product_currency_symbol": "$",
║ "count": 1,
║ "product_img": "https://ib293feae9ac429383c8088f7da503c6.
║ jpg"
║ },
║ {
║ "product_id": "id_0001_0002",
║ "product_name": "PUBG Mobile",
║ "count": 5,
║ "product_price": 299.99,
║ "product_currency_symbol": "$",
║ "product_img": "https://ib293feae9ac429383c8088f7da503c6.
║ jpg"
║ },
║ {
║ "product_id": "id_0001_0003",
║ "product_name": "PUBG Mobile id_0001_0003",
║ "count": 26,
║ "product_price": 399.99,
║ "product_currency_symbol": "$",
║ "product_img": "https://i9b293feae9ac429383c8088f7da503c6.
║ jpg"
║ },
║ {
║ "product_id": "id_0001_0004",
║ "product_name": "PUBG Mobile id_0001_0004",
║ "count": 13,
║ "product_price": 499.99,
║ "product_currency_symbol": "$",
║ "product_img": "https://i9b293feae9ac429383c8088f7da503c6.
║ jpg"
║ }
║ ]
║ }

╚══════════════════════════════════════════════════════════════════════════════════════════╝

Actual Result

image

@pangli pangli added h: need triage This issue needs to be categorized s: bug Something isn't working labels Jan 6, 2025
@AlexV525
Copy link
Member

AlexV525 commented Jan 7, 2025

Both "override transformer" and "transformer = ..." work.

image
image

@AlexV525 AlexV525 closed this as not planned Won't fix, can't repro, duplicate, stale Jan 7, 2025
@AlexV525 AlexV525 added i: not related and removed h: need triage This issue needs to be categorized s: bug Something isn't working labels Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants