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

如何将Access Token从登录页传递至资料修改页并调用API

解决方法

要让你的updateProfile方法携带登录时获取的Access Token,需按以下步骤调整:

1. 先存储登录成功后的Token

登录接口返回Access Token后,将其保存在本地(推荐使用shared_preferences包),示例代码如下:

import 'package:shared_preferences/shared_preferences.dart';

// 登录成功后调用此方法存储Token
Future<void> saveAccessToken(String token) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('access_token', token);
}

2. 修改updateProfile方法

在请求头中添加Authorization字段,携带存储的Token:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> updateProfile() async {
  String url = "http:///myprofile/${userId}/";

  // 构建用户资料参数
  Map<String, String> queryParams = {
    "email": _emailController.text,
    "password": passwordController.text,
    "repassword": repasswordController.text,
    "firstname": firstname.text,
    "lastname": lastname.text,
    "phonenumber": phonenumber.text,
    "state": state.text,
    "city": city.text,
    "Zip": zip.text,
    "mailing": _value.toString(),
    "referred_by": selectedItem,
    "flag": "business",
    "businessname": businesscontroller.text,
  };
  String queryString = Uri(queryParameters: queryParams).query;
  url += '?' + queryString;

  // 读取本地存储的Access Token
  final prefs = await SharedPreferences.getInstance();
  String? accessToken = prefs.getString('access_token');

  try {
    final response = await http.put(
      Uri.parse(url),
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer $accessToken", // 核心:添加Token到请求头
        "User-Agent": "PostmanRuntime/7.28.4",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
      },
    );

    var data = jsonDecode(response.body);

    print(url);
    print(response.statusCode);
    print(data);

    if (response.statusCode == 200) {
      _showSuccessDialog();
      Navigator.push(
        context,
        MaterialPageRoute(builder: (_) => BottomPage()),
      );
    } else {
      _showErrorDialog('Failed to update profile. Please try again.');
    }

    print(response.body);
  } catch (e) {
    print('Error updating profile: $e');
    _showErrorDialog('Failed to update profile. Please try again.');
  }
}

补充说明

  • 若后端不使用Bearer Token格式,可直接调整Authorization字段的值(比如仅传Token字符串)。
  • 需在pubspec.yaml中添加依赖:
    dependencies:
      shared_preferences: ^2.2.2
    
  • 可根据后端返回的401状态码,添加Token过期后的重新登录逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:35:55