After i logged in successfully i got access token, and i'm passing that accestoken using SharedPerference to another screen, i am getting values too in my header and data, but it gives me this error
Error:
type 'String' is not a subtype of type 'int' of 'index'
here is my code
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);
});
}
i am calling this method on button click. please help if anyone know how to fix it.
You can use app 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);
}
}
}
Make an object of Dio also give a base URL
final Dio dio = Dio(BaseOptions(baseUrl: baseUrl,));
Then call get function, pass existing url and pass token through headers like this
final Response response = await dio.get(url, options: Options(headers:{"Authorization":"Bearer $token"},));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With