【发布时间】:2021-04-08 12:12:22
【问题描述】:
我有一个函数,它返回用户令牌,并将其保存到共享首选项,如果存在令牌,则将其保存到 SP。另一种方法等待令牌,如果令牌存在,则对用户进行身份验证 这是我的代码
login(username, password) async {
final String url = "http://10.0.2.2:8080/api/auth/signin"; // iOS
final http.Response response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'username': username,
'password': password,
}),
);
LoginModel userSave = loginModelFromJson(response.body);
print(response.body);
final SharedPreferences prefs = await SharedPreferences.getInstance();
bool result = await prefs.setString('user', jsonEncode(userSave));
print(result);
}
这段代码按预期工作,但我在从 Future 获取令牌值时遇到问题。 案例场景:用户输入用户名和密码并通过服务器进行身份验证。如果帐户存在,则从服务器生成令牌并发送到应用程序并存储在共享首选项中。令牌(如果可用)是从共享首选项中选择并用于登录应用程序,但令牌的检查是在生成和保存之前完成的
Future<LoginModel> getUserInfo() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, dynamic> userMap;
final String userStr = prefs.getString('user');
if (userStr != null) {
userMap = jsonDecode(userStr) as Map<String, dynamic>;
}
if (userMap != null) {
final LoginModel user = LoginModel.fromJson(userMap);
print(user);
return user;
}
return null;
}
令牌在保存之前被调用,抛出 null 错误
RoundedButton(
text: "LOGIN",
press: () async {
if (_formKey.currentState.validate()) {
progressDialog.show();
await login(
username,
password,
);
SharedPreferences prefs =
await SharedPreferences.getInstance();
String token = prefs.getString("accessToken");
getUserInfo();
// ignore: null_aware_in_condition
if (token == null) {
progressDialog.hide();
showAlertsDialog(context);
// ignore: null_aware_in_condition
} else {
progressDialog.hide();
showAlertzDialog(context);
}
}
},
),
我相信有非常小的逻辑错误,但我自己找不到。
【问题讨论】:
-
你能把它减少到最小的可重现情况吗?要导航的代码很多。
-
嗨 @RandalSchwartz 已将其最小化