创建新用户后尝试获取当前用户信息,但在尝试调用“.currentUser()”方法时出现此错误“无法无条件调用该函数,因为它可以为‘null’”如何解决此问题?
这是尝试调用“final user=await _auth.currentUser();”时发生错误的代码
enter code here
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class RegistrationScreen extends StatefulWidget {
@override
_RegistrationScreenState createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
final _auth =FirebaseAuth.instance;
late String eMail;
late String password;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
height: 200.0,
child: Image.asset('images/logo.png'),
),
SizedBox(
height: 48.0,
),
TextField(
onChanged: (value) {
//Do something with the user input.
eMail=value;
},
),
SizedBox(
height: 8.0,
),
TextField(
onChanged: (value) {
//Do something with the user input.
password=value;
},
),
SizedBox(
height: 24.0,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
color: Colors.blueAccent,
borderRadius: BorderRadius.all(Radius.circular(30.0)),
elevation: 5.0,
child: MaterialButton(
onPressed: () async {
try{
final _newUser= await _auth.createUserWithEmailAndPassword(email: eMail, password: password);
if(_newUser!=null)
{
final user=await _auth.currentUser();
}
}
catch(e)
{
print(e);
}
},
minWidth: 200.0,
height: 42.0,
child: Text(
'Register',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
),
);
}
}
问题是我正在调用“final user =_auth.currentUser()”函数,该函数已更改为“final user =_auth.currentUser” currentUser 是一个吸气剂,也不需要等待关键字并从中获取电子邮件、uid 等我们应该检查的用户 如果用户为空,则访问电子邮件和 uid 等。
enter code here
final _newUser= await _auth.createUserWithEmailAndPassword(email: eMail, password: password);
if(_newUser!=null)
{
final user =_auth.currentUser;
if(user!=null)
{
final email = user.email;
print(email);
}
}
正如错误所示,您应该添加一个空检查,如下所示:
filan user = await _auth!.currentUser();
因为
_auth
可以为空。您也可以使用此代码:
filan user = await _auth?.currentUser() ?? User(); // the name of user class