为了保持用户登录 flutter 应用程序,我想在
SharedPreferences
中保存来自 API 响应的令牌。我正在尝试保存它,但这不起作用。
基本上,API 响应已成功接收及其登录令牌,但如何保存在用户登录的共享首选项中 重新打开应用程序后,我正在处理它,但保存得不好
这是我在
whereGoTo
钩子中初始化的启动屏幕方法 initState
:
void whereGoTo() async {
var sharedPref = await SharedPreferences.getInstance();
var isSignedIn = sharedPref.getString('token');
Timer(Duration(seconds: 2), () {
if (isSignedIn != null && isSignedIn.isEmpty) {
print(isSignedIn);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomePage()));
} else {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SafeArea(child: Login_Screen())));
}
});
}
这里我的
signIn
方法集成了API和setString方法来在api响应后保存令牌:
String? myToken;
loginApi(email, password) async {
print(email);
print(password);
final response = await http
.post(Uri.parse('https://quotes.limpidsol.com/api/login'), body: {
'email': email,
'password': password,
});
if (response.statusCode == 200) {
print('account loggedIn successfully');
var data = ExtructData.fromJson(jsonDecode(response.body));
print(data.token);
setState(() {
myToken = data.token;
});
var pref = await SharedPreferences.getInstance();
pref.setString('token', myToken!);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomePage()));
String successMessage =
'Logged in successfully. Status code: ${response.statusCode}';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(successMessage),
),
);
} else {
String errorMessage = 'Login failed. Status code: ${response.statusCode}';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
),
);
}
}
此行后面的
isSignedIn
参数中是否有正确的标记值var isSignedIn = sharedPref.getString('token');
?
正如我在你的代码中看到的,错误在于条件:而不是
if (isSignedIn != null && isSignedIn.isEmpty) {
应该是
if (isSignedIn != null && isSignedIn.isNotEmpty) {
PS 最好使用一些安全存储来存储令牌 - 例如 flutter_secure_storage 包