You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何存储Rest API返回的Authorization Token并用于其他接口请求头

问题根因

你的问题核心是没有处理异步方法的等待逻辑:
writeSecureToken和readSecureToken都是返回Future的异步方法,你调用时没有加await关键字,导致拿到的是Future实例而非实际的Token值,也无法保证存储操作完成后才执行后续逻辑。

修复步骤

1. 修复注册接口的Token存储逻辑

找到注册接口中存储Token的代码,添加await关键字:

if (response.statusCode == 201) {
  print('Response Body: ${response.body}');
  final data = jsonDecode(response.body);

  // 新增await等待存储完成
  await storage.writeSecureToken('key', data['key']);
  // 可添加调试代码验证存储结果
  String? savedToken = await storage.readSecureToken('key');
  print("存储成功的Token: $savedToken");

  return UserRegistration(
    key: data['key'],
    status: true,
  );
}

2. 修复OTP校验接口的Token读取逻辑

读取Token时同样添加await关键字,确保拿到实际的Token字符串再拼接请求头:

Future<PhoneOTPValidate> phoneOTPvalidate(dynamic param) async {
  var client = http.Client();
  // 新增await等待读取完成
  var token = await storage.readSecureToken('key');
  // 增加空判断避免异常
  if (token == null) {
    throw Exception('未获取到有效凭证,请重新注册');
  }
  try {
    var response = await client
        .post(
            Uri.https("baseURL", "endpoint"),
            headers: <String, String>{
              'Authorization': 'Token $token',
            },
            body: param)
        // 其余原有逻辑保持不变

可选优化建议

建议将SecureStorage封装为单例,避免重复实例化带来的潜在问题:

class SecureStorage {
  final storage = FlutterSecureStorage();
  // 单例实现
  static final SecureStorage _instance = SecureStorage._internal();
  factory SecureStorage() => _instance;
  SecureStorage._internal();

  Future writeSecureToken(String key, String value) async {
    return await storage.write(key: key, value: value);
  }

  Future<String?> readSecureToken(String key) async {
    return await storage.read(key: key);
  }

  Future deleteSecureToken(String key) async {
    return await storage.delete(key: key);
  }
}

内容的提问来源于stack exchange,提问作者needHelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 07:12:01