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
相关产品推荐
相关产品推荐

