Files
ln-ios/ln_jq_app/lib/common/token_interceptor.dart
2025-11-05 17:21:03 +08:00

31 lines
1.0 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:dio/dio.dart';
import 'package:ln_jq_app/storage_service.dart';
/// 专门用于处理和添加 Token 的拦截器
class TokenInterceptor extends Interceptor {
// 定义您想要使用的 Token Key
final String tokenKey;
// 构造函数,允许外部传入自定义的 Key默认为 'Authorization'
TokenInterceptor({this.tokenKey = 'Authorization'});
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
// 从 StorageService 中获取已保存的 token
final String? token = StorageService.to.token;
// 如果 token 存在,就添加到请求头中
if (token != null && token.isNotEmpty) {
// 检查请求头中是否已存在这个key避免重复添加
if (!options.headers.containsKey(tokenKey)) {
// 使用我们自定义的 key 添加 token
options.headers[tokenKey] = token;
}
}
// 调用 handler.next(options) 以继续执行请求
// 这一步至关重要,否则请求会被中断
super.onRequest(options, handler);
}
}