我有这个未来的方法,我正在尝试实现为在flutter中充当HTTP拦截器!
仅在第二次单击按钮后才能使用!。
class AppInterceptor {
Dio dio = Dio();
AuthService auth = AuthService();
Future setInterceptor() async {
var token;
auth.user.listen((auth) => {
if (auth != null)
{
print('called'),
auth.getIdToken().then((tok) => {
token = tok,
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options) {
// Do something before request is sent
dio.options.contentType =
ContentType.parse("application/json");
options.headers["Authorization"] = 'Bearer $token';
print(token);
return options;
}, onResponse: (Response response) {
// Finally, the string is parsed into a JSON object.
return response;
}, onError: (DioError e) {
print(e.message);
return e;
}))
})
}
});
}
}
我在请求中按如下方式呼叫拦截器:
AppInterceptor appInterceptor = AppInterceptor();
Future onSubmit() async {
await appInterceptor.setInterceptor();
Response response =
await appInterceptor.dio.get('$functionsUrl/app/clienttoken/');
//print(response);
......
}
现在,第一次单击onSubmit()
时,它会记录一个错误:
表示此请求,因为缺少用户令牌而无法接受请求!
但是,第二次点击效果很好。
该如何解决?