所以我使用rest api作为后端,我无法编辑,所以我发现需要传递令牌,从登录到此更改配置文件api,以便用户可以成功编辑他或她的详细信息。
Future<void> updateProfile() async {
String url = "http:///myprofile/${userId}/";
// Build the query parameters with updated user information
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;
try {
final response = await http.put(
Uri.parse(url),
headers: {
"Content-Type": "application/json",
"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) {
// Success
_showSuccessDialog();
// Navigate to the next page or perform any other actions
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => BottomPage(),
),
);
} else {
// Error
_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.');
}
}
我附上了我尝试过的上面的代码片段 我需要修改它,使其可以从成功登录中访问令牌,这可以帮助编辑信息。
这应该有帮助
final token = "your-backend-token";
final response = await http.put(
Uri.parse(url),
headers: {
"Content-Type": "application/json",
"User-Agent": "PostmanRuntime/7.28.4",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
HttpHeaders.authorization: token,
},
);
另外你也可以有这样的东西
class ApiHandler {
ApiHandler.instance(); // for instantiating request withou token
String? _token;
ApiHandler.tokenInstance() {
_token = getToken() ?? throw "No Token found";
// `getToken()` gets token from shared preferences or wherever you have stored.
}
// use this for public api requests
Map<String, String> get jsonHeaders = {
HttpHeaders.contentType: "application/json",
}
// use this for authorized api requests
Map<String, String> get tokenHeaders = {
HttpHeaders.contentType: "application/json",
HttpHeaders.authorization: _token,
}
// your other api request methods
}
您需要使用 SharedPreferences 包来存储成功登录后的令牌:
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('token', '$<yourToken>');
然后当您需要访问令牌时只需调用:
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
您可以通过 3 种方式做到这一点:
您可以创建一个包含此变量的全局文件,并将其导入到将要访问的任何位置。这可确保只要应用程序未重新启动,您就拥有相同的令牌。重启后,变量会再次重置
同样,您使用 flutter.dev 的 shared_preferences 插件,您可以将数据永久存储在每台机器上。
需要注意的是:使用此方法时,您将需要处理 SharedPreferences 的异步初始化。初始化后,读取调用不是异步的
final SharedPreferences prefs = await SharedPreferences.getInstance();
这会有点麻烦,我不会推荐它用于您的用例,但它仍然是一个选项。以下是如何使用 StatefulWidget 执行此操作的示例:
class ProfileOptions extends StatefulWidget {
const ProfileOptions({super.key, required this.id});
final String id;
@override
State<Product> createState() => _ProfileOptionsState();
}
class _ProfileOptionsState extends State<ProfileOptions> {
late String id;
@override
void initState() {
super.initState();
id = widget.id;
}}
@override
Widget build(BuildContext context) {
return Placeholder();
}
}
您还可以将令牌作为函数的参数传递。这将要求您在调用函数的位置存储和访问令牌(因此您仍然需要执行 1, 2, 3.1 或者您需要将函数存储在与变量相同的文件中,然后您可以从函数内部访问变量)
Future<void> updateProfile(String authToken) async {
// Your code
}