我宣告了 _auth 并在注冊按鈕中呼叫了它,所以它將我帶到另一個螢屏,但我收到一條警告說:
“運算元不能為空,因此條件始終為真。”
請幫我解決這個問題,我真的完全不明白這個問題。
final _auth = FirebaseAuth.instance; //This is where I declared the auth variable
late String email;
late String password;
RoundedButton(
color: Colors.blueAccent,
title: 'Register',
onPress: () async {
try {
final newUser =
await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (newUser != null) { //This is where the warning comes from
if (!mounted) return;
Navigator.pushNamed(context, ChatScreen.id);
}
} catch (e) {
print(e);
}
},
),
uj5u.com熱心網友回復:
await _auth.createUserWithEmailAndPassword(email: email, password: password)
will 回傳一個UserCredential
物件,它永遠不會為 null,因此對其設定 if else
條件實際上并沒有做任何事情,因為newUser != null
will 始終等于true
。
你寫的這段代碼等同于:
final _auth = FirebaseAuth.instance; //This is where I declared the auth variable
遲到的字串電子郵件;晚字串密碼;
RoundedButton(
color: Colors.blueAccent,
title: 'Register',
onPress: () async {
try {
final newUser =
await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (!mounted) return;
Navigator.pushNamed(context, ChatScreen.id);
} catch (e) {
print(e);
}
},
),
我假設您想捕獲可能從此 auth 操作拋出的例外/錯誤,例如invalid-email
, weak-password
, email-already-in use
,因為您需要使用Exception
Firebase Auth 的特殊類來捕獲FirebaseAuthException
,所以您的代碼現在應該是這樣的:
late String email;
late String password;
RoundedButton(
color: Colors.blueAccent,
title: 'Register',
onPress: () async {
try {
final newUser =
await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (!mounted) return;
Navigator.pushNamed(context, ChatScreen.id);
} on FirebaseAuthException catch (e) {
print(e.code);
print(e.message);
}
},
),
現在,看看那一行:
final newUser =
await _auth.createUserWithEmailAndPassword(email: email, password: password);
按預期創建一個新用戶,然后它將回傳該請求的結果,該請求UserCredentail
包含一些特定用戶的資訊,例如電子郵件、訪問令牌、uid ...,因此如果您創建了用戶帳戶然后保存UserCredentail
而不使用它,它會顯示一個警告(不是真正的錯誤):
The value of the local variable isn’t used In Dart
現在,如果我們像這樣使用該變數作為示例:
print(newUser);
警告將消失,因為它現在已被使用。
如果您不打算在實際專案中使用該變數,那么您可以createUserWithEmailAndPassword
這樣呼叫:
await _auth.createUserWithEmailAndPassword(email: email, password: password);
如果不將其保存在變數中,它將按預期為用戶創建一個新帳戶。
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537193.html
標籤:Google Cloud Collective 安卓扑火力基地镖
上一篇:錯誤:型別不匹配:推斷型別是Map<String,String>?但是在Flutter/Kotlin中使用MethodChannel時預期Map<String,String>