0

我正在尝试将令牌传递给标头。我正在从我的共享偏好中访问令牌。数据已成功保存至偏好。但是在网络调用中,它在开始时传递一个空值,但在返回并重新打开页面后工作正常。

我的错误:

E/flutter (23190): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'accessToken' was called on null.


  E/flutter (23190): Receiver: null
    E/flutter (23190): Tried calling: accessToken
    E/flutter (23190): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
    E/flutter (23190): #1      NetworkUtil.get (package:example/apihandler/network/NetworkUtil.dart:55:52)

我的网络课堂

class NetworkUtil {
  Dio _dio;
String token;
  LoginResponse loginResponse;




  NetworkUtil() {
    ///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
    BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
    options.baseUrl = ApiConstants.BASE_URL;
    _dio = Dio(options);

      AppPrefernces.getLoginPref().then((data) {
        this.loginResponse = LoginResponse.fromJson(jsonDecode(data));
      });

      
    _dio.interceptors.add(LogInterceptor());

  }





  ///used for calling Get Request
  Future<Response> get(String url, Map<String, String> params) async {
    Response response = await _dio.get(url,
        queryParameters: params,
        options: Options(responseType: ResponseType.json,headers: {
          "Authorization": "Bearer ${loginResponse.accessToken==null?"":loginResponse.accessToken}"
        }));
    return response;
  }

  ///used for calling post Request
  Future<Response> post(String url, Map<String, dynamic> params) async {
    Response response = await _dio.post(url,
        data: params, options: Options(responseType: ResponseType.json));
    return response;
  }
}

这是我的 Sharedpreference 文件:

class AppPrefernces {
  static final String LOGIN_PREF = "login";

  static Future<String> getLoginPref() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.get(LOGIN_PREF) ?? null;
  }



  static setLoginPref(String value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(LOGIN_PREF, value);
  }
}
4

2 回答 2

0

在您的构造函数 NetworkUtil() 中,您在使用令牌设置 loginResponse 之前进行了异步操作。当您进行 API 标注时,它还没有完成。您应该重新设计 NetworkUtil 启动并添加一个标志以了解它是否已准备好使用。

您可以使用git_it并为您的 NetworkUtil 创建异步惰性单例。

于 2020-09-07T10:23:32.913 回答
0

当您调用该get方法时,loginResponse 值尚未分配。

class NetworkUtil {
  Dio _dio;
  String token;
  LoginResponse loginResponse;

  NetworkUtil() {
    ///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
    BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
    options.baseUrl = ApiConstants.BASE_URL;
    _dio = Dio(options);

    _dio.interceptors.add(LogInterceptor());
  }

  ///used for calling Get Request
  Future<Response> get(String url, Map<String, String> params) async {
    loginResponse ??= LoginResponse.fromJson(jsonDecode(await AppPrefernces.getLoginPref()));

    Response response = await _dio.get(url,
        queryParameters: params,
        options: Options(responseType: ResponseType.json, headers: {
          "Authorization": "Bearer ${loginResponse.accessToken == null ? "" : loginResponse.accessToken}"
        }));
    return response;
  }

  ///used for calling post Request
  Future<Response> post(String url, Map<String, dynamic> params) async {
    Response response = await _dio.post(url, data: params, options: Options(responseType: ResponseType.json));
    return response;
  }
}
于 2020-09-07T10:24:22.693 回答