gpt4 book ai didi

firebase - Flutter - 异步函数返回 null

转载 作者:IT王子 更新时间:2023-10-29 07:09:32 26 4
gpt4 key购买 nike

我已经断断续续地研究了几天,即使在搜索和挖掘之后,也没有弄明白。

下面是两段相关的代码:

Future<FirebaseUser> signUp(String email, String password, String username) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password).then((newUser) {
var obj = {
"active": true,
"public": true,
"email": email,
"username":username
};
_profileRef.child(newUser.uid).set(obj).then((_) {
print("inside");
//print("new userId: ${newUser}");
//return newUser;
});
});
//print("outside");
return user;
}

并且:

Future<void> register() async {
final formState = _formKey.currentState;

if(formState.validate()) {
formState.save();

try {
//print("email: " + _email + ", pwd: " + _password);
//FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email,password: _password);
//String uid = await widget.auth.signIn(_email, _password);
FirebaseUser user = await widget.auth.signUp(_email, _password, _username);

print("uid: " + user.uid);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage(auth: widget.auth, userId: user.uid, onSignedOut: widget.onSignedIn,)));
//Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage(auth: widget.auth, userId: uid, onSignedOut: widget.onSignedIn,)));
} catch(e) {
print(e);
}
}
}

signUp() 函数正常工作,并在 Firebase 中正确创建用户,以及 Firebase 实时数据库中的 userProfile 条目。但是,无论出于何种原因,我都无法在 register() 函数中取回实际的 FirebaseUser 对象。它总是返回如下错误:

    Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 1.315s, DNS @0.001s took 0.004s, TCP @0.007s took 0.053s, TLS took 0.158s
bytes in/out: 5745/975, packets in/out: 9/9, rtt: 0.051s, retransmitted packets: 0, out-of-order packets: 0
[C3.1 8282B933-6D0B-4103-937C-173268FD0304 192.168.1.7:54700<->172.217.14.106:443]
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 0.441s, DNS @0.000s took 0.003s, TCP @0.005s took 0.054s, TLS took 0.152s
bytes in/out: 5040/1812, packets in/out: 9/9, rtt: 0.052s, retransmitted packets: 0, out-of-order packets: 0
flutter: NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
flutter: inside

最佳答案

awaitthen 结合使用通常会造成混淆。重构您的 signUp 方法以删除 then

Future<FirebaseUser> signUp(String email, String password, String username) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
var obj = {
"active": true,
"public": true,
"email": email,
"username": username,
};
await _profileRef.child(user.uid).set(obj);
return user;
}

关于firebase - Flutter - 异步函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55083338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com