如何在flutter中使用dio在报头中传递访问令牌



在我成功登录后,我获得了访问令牌,并且我正在使用SharedPerference将该访问令牌传递到另一个屏幕,我在我的头和数据中也获得了值,但它给了我这个错误

错误:type 'String' is not a subtype of type 'int' of 'index'

这是我的代码

var localhostUrlTimeIn="http://10.0.2.2:8000/TimeIn";
timeIn() async {
Dio dio=new Dio();
//dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"]="token ${getaccesstoken}";
var data={
'username': getname,
};
await dio
.post(localhostUrlTimeIn,data: json.encode(data),
)
.then((onResponse)  async {
print(onResponse.data['message']);

}).catchError((onerror){
print(onerror.toString());
//showAlertDialog(context);
});

}

我在点击按钮时调用这个方法。如果有人知道如何修复,请帮忙。

您可以使用应用程序AppInterceptors

final _dio = Dio();
_dio.options.baseUrl = ApiPath.base_Url;
_dio.options.receiveTimeout = 3000;
_dio.interceptors.add(AppInterceptors());
class AppInterceptors extends InterceptorsWrapper {
GlobalKey<NavigatorState> navigator;
@override
Future onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
print(options.baseUrl + options.path);
AuthService auth = new AuthService();
var accessToken = await auth.getToken();
if (accessToken == null) {
log('trying to send request without token exist!');
return super.onRequest(options, handler);
}
options.headers["Authorization"] = "Bearer " + accessToken.toString();
return super.onRequest(options, handler);
}
@override
onResponse(Response response, ResponseInterceptorHandler handler) {
return super.onResponse(response, handler);
}
@override
onError(DioError err, ErrorInterceptorHandler handler) {
// var url = err.request.uri;
print("************************************************");
print(err);
super.onError(err, handler);
if (err.response.statusCode == 401) {
AuthService authservice = new AuthService();
authservice.logout();
locator<NavigationService>().navigateTo(Routes.root);
}
}
}

使用拦截器是更好的方法。要做到这一点,你可以在这里的文档上阅读。

但是,如果您还想处理令牌刷新,fresh_dio是一个很好的包,既可以将令牌添加到头中,也可以在令牌过期时刷新它。

使Dio的对象也给出一个基本URL

final Dio dio = Dio(BaseOptions(baseUrl: baseUrl,));

然后调用get函数,通过像这样的头传递现有的url和令牌

final Response response = await dio.get(url, options: Options(headers:{"Authorization":"Bearer $token"},));

最新更新