You need to enable JavaScript to run this app. Flutter:如何将响应头返回的Token存储至SharedPreferences
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:如何将响应头返回的Token存储至SharedPreferences

实现方案

核心操作逻辑

  • 直接通过response.headers根据后端约定的Token字段名取值(dart的http包头信息是大小写不敏感映射,无需纠结字段大小写)
  • 调用已初始化的SharedPreferences实例的setString方法持久化Token
  • 同步修正你现有代码中的缺失逻辑(响应体解析、错误分支处理、参数类型错误)

修正后完整代码

Future<DriverModel> _handleLogin(int country_code, int phone, String password) async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  Map<String, dynamic> data = {
    'phone': {
      'country_code': country_code,
      'phone': phone,
    },
    'password': password,
  };
  var body = json.encode(data);
  final response = await http.post(
    AuthApi.login,
    headers: {"Content-Type": "application/json"},
    body: body,
  );

  // 统一解析响应体
  var jsonData = json.decode(response.body);

  if (response.statusCode == 200) {
    // 替换为后端实际返回的Token字段名,常见的有token、Authorization、X-Auth-Token等
    final token = response.headers['token'];
    // 非空时才存储
    if (token != null) {
      await sharedPreferences.setString('token', token);
    }
    return DriverModel.fromJson(jsonData);
  } else {
    // 可根据业务扩展错误提示逻辑,比如抛出异常或返回错误实体
    throw Exception('登录失败,状态码:${response.statusCode}');
  }
}

补充说明

  • 修正了原代码中参数类型Int的错误写法,Dart内置整数类型为小写int
  • 若后端响应头的Token是带Bearer前缀的格式(比如Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9),可根据业务需求决定是完整存储还是提取Bearer 之后的纯Token部分存储
  • 后续其他接口需要携带Token时,可通过sharedPreferences.getString('token')读取已存储的值,放入请求头即可
  • 如果你需要退出登录时清除Token,调用sharedPreferences.remove('token')即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 19:24:04