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