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

I don't know where the problem is with my code. After handler.reslove(res), the return value of the original request is always empty. #2090

Closed
jackie-weiwei opened this issue Jan 9, 2024 · 3 comments

Comments

@jackie-weiwei
Copy link

jackie-weiwei commented Jan 9, 2024

Request Statement

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class RestApi {
  late Dio _dio;
  late Dio _dio2;
  late String _token;
  late String _token2;
  get dio => _dio;
  static final RestApi _instance = RestApi._interal();
  factory RestApi() => _instance;
  RestApi._interal() {
    _dio = Dio();
    _dio2 = Dio();
  }
  void readToken() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String? token = pref.getString("token");
    String? token2 = pref.getString("token2");
    if (token == null) {
      _token = "";
    }
    if (token2 == null) {
      _token2 = "";
    }
  }
  void saveToken() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString("token", _token);
    pref.setString("token2", _token2);
  }
  init(
      {String? baseUrl,
      int? connectTmo,
      int? receiveTmo,
      int? sendTmo,
      String? pem}) async {
    readToken();
    baseUrl = baseUrl ?? "";
    connectTmo = connectTmo ?? 0;
    receiveTmo = receiveTmo ?? 0;
    sendTmo = sendTmo ?? 0;
    BaseOptions option = BaseOptions(
        baseUrl: baseUrl,
        connectTimeout: Duration(seconds: connectTmo),
        receiveTimeout: Duration(seconds: receiveTmo),
        sendTimeout: Duration(seconds: sendTmo));
    _dio = Dio(option);
    _dio2 = Dio(option);
    if (pem != null) {
      _dio.httpClientAdapter = IOHttpClientAdapter(
        createHttpClient: () {
          final client = HttpClient(
            context: SecurityContext(withTrustedRoots: false),
          );
          client.badCertificateCallback = (cert, host, port) => true;
          return client;
        },
        validateCertificate: (cert, host, port) {
          if (cert == null) return false;
          return cert.pem == pem;
        },
      );
      _dio2.httpClientAdapter = IOHttpClientAdapter(
        createHttpClient: () {
          final client = HttpClient(
            context: SecurityContext(withTrustedRoots: false),
          );
          client.badCertificateCallback = (cert, host, port) => true;
          return client;
        },
        validateCertificate: (cert, host, port) {
          if (cert == null) return false;
          return cert.pem == pem;
        },
      );
    }
    _dio.interceptors.add(QueuedInterceptorsWrapper(
      onRequest: (options, handler) async {
        options.headers["access"] = _token;
        return handler.next(options); //continue
      },
      onResponse: (response, handler) {
        debugPrint(response.requestOptions.path);
        String path = response.requestOptions.path;
        if (path.contains("login")) {
          _token = response.data["accessToken"];
          _token2 = response.data["refreshToken"];

          debugPrint(response.data);
        }
        return handler.next(response); // continue
      },
      onError: (error, handler) async {
        if (error.response?.statusCode == 401) {
          bool bSucc = await refreshToken();
          if (bSucc) {
            var res = await _dio.fetch(error.response!.requestOptions);
            handler.resolve(res); //continue
          } else {
            handler.next(error);
          }
        } else {
          handler.next(error);
        }
      },
    ));
  }

  Future post({
    required String path,
    dynamic data,
    Map<String, dynamic>? queryParameters,
  }) {
    Options options = Options(
      method: "post",
    );
    return _dio.request(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }
  Future<bool> refreshToken() async {
    Options options = Options(
      method: "post",
      headers: {"refresh": _token2},
    );
    Response response = await _dio2.request(
      "/refresh_token/refresh",
      data: {"mobile": "138999999999"},
      options: options,
    );
    _token = response.data["access"];
    return true;
    // try {} on DioException catch (_) {
    //   return false;
    // } finally {}
  }
}

Solution Brainstorm

No response

Tasks

No tasks being tracked yet.
@jackie-weiwei jackie-weiwei added the s: feature This issue indicates a feature request label Jan 9, 2024
@jackie-weiwei
Copy link
Author

image

@jackie-weiwei
Copy link
Author

I'm at my wits' end, please help.

@AlexV525
Copy link
Member

AlexV525 commented Jan 9, 2024

Please provide a minimal reproducible example rather than nested implementations, and use discussions for general issues. Also the template is for feature requests.

@AlexV525 AlexV525 closed this as not planned Won't fix, can't repro, duplicate, stale Jan 9, 2024
@AlexV525 AlexV525 added i: not related and removed s: feature This issue indicates a feature request labels Jan 9, 2024
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