![](/img/trans.png)
[英]How to structure a model in Flutter and Firebase after null safety
[英]Firebase Auth failing with null safety
我有一個 Firebase 授權登錄 function,我不得不更改一些代碼以允許null safety
Auth
function 的這個特定部分被證明是棘手的
Future<String> getCurrentUser() async {
User? user = await _firebaseAuth.currentUser;
return user!.uid;
}
在我運行之前,我的代碼沒有錯誤。 然后它在return
語句上失敗,其中Null check operator used on a null value
。
這是當沒有用戶登錄時,因此沒有當前用戶可返回。
我必須安全地安裝 null 但在這樣做時 null 檢查正在完成它的工作,看到沒有當前用戶並且失敗。
然后我可以在模擬器上按“播放”,代碼在 sim 上運行良好,但在生產中這不起作用,需要修復。
當我在沒有用戶登錄的情況下再次按下重新啟動時,它失敗了,按下“播放”似乎讓它很開心,盡管只返回了null
,但它工作正常。
有辦法解決這個問題嗎? 我試過if
但我仍然需要return user.;uid;
在最后
任何幫助表示贊賞,謝謝
所有應用程序的理想實現是使用authStateChanges()來使用身份驗證 state 觀察器。 只要知道用戶已完全登錄或注銷,這就會給您一個回調。 這將使您可以根據 state 調整您的 UI。正確實施后,這將為您提供一種立即響應用戶 state 的方法,並且如果用戶 object 之前已登錄並且還會為您提供用戶 object 首先可用的時刻剛剛再次啟動該應用程序。
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
要清楚:不要使用 currentUser,除非您只需要快速檢查用戶在 state 中的登錄。最好聽取隨時間的變化並在它們發生時做出響應。
如果用戶是 null,您可以返回一個空字符串。
Future<String> getCurrentUser() async {
User? user = await _firebaseAuth.currentUser;
if(user != null){
return user!.uid;
} else {
return "";
}
}
然后當你調用你的方法時,你可以檢查結果是否為空:
String userId = await getCurrentUser();
if(userId != ""){
// Do stuff when user is logged in
} else{
// Do stuff when user is not logged in
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.