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

时间:2021-06-08 09:18:11

标签: flutter post header 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);
    });

    
  }

我在单击按钮时调用此方法。如果有人知道如何修复它,请帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用应用程序 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);
    }
  }
}

答案 1 :(得分:0)

使用拦截器是更好的方法。为此,您可以阅读文档 here

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