我有一個獲取用戶登錄狀態的功能,現在我想在被選中的用戶沒有登錄時添加一個靜默登錄的邏輯。 用戶登錄后,我將用戶名和密碼的登錄資訊存盤到用戶后的本地安全存盤中第一次登錄,呼叫islogin函式時,我的代碼是這樣的:
bool get isLogin {
if(this == null){
// not login, do the automatic login logic
final UserAccount userAccount = UserAccount();
final String? phone = await SecureStorageUtil.getString("username");
final String? password = await SecureStorageUtil.getString("password");
if(phone == null || password == null){
return false;
}
final Result<Map> result = await userAccount.login(phone, password);
if(result != null){
return true;
}
}
return this != null;
}
讓我卡住的是獲取憑證資訊和登錄是異步的,并且必須使用 await 關鍵字來等待回傳。但是 await 關鍵字只允許在 async 函式中使用。
The await expression can only be used in an async function.
如果我將isLogin函式更改為 async,則此專案中的許多地方必須更改。我想知道是否可以在同步功能中使用 await ?所以如果用戶只登錄一次,我可以進行自動登錄。并且沒有對之前的代碼做任何改動。
uj5u.com熱心網友回復:
嘗試將您的功能簽名替換為
Future<bool> get isLogin async {
uj5u.com熱心網友回復:
Timer timer;
@override
void initState() {
super.initState();
timer = new Timer.periodic(new Duration(seconds: 1), (Timer timer) async {
await this.getUserVerificationInfo();
});
}
@override
void dispose() {
super.dispose();
timer.cancel();
}
getUserVerificationInfo() async {
await someAsyncFunc();
timer.cancle();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342559.html
