用户已使用firebase电子邮件登录登录到应用程序。如何使appbar标题成为当前用户的电子邮件?
class _HomePageState extends State<HomePage> {
final Future<String> userEmail = FirebaseAuth.instance.currentUser().then((FirebaseUser user) => user.email);
var e = "";
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.black,
title: Text('userEmail'),
actions: <Widget>[
new FlatButton(
onPressed: _signOut,
child: new Text('logout', style: new TextStyle(fontSize: 17.0, color: Colors.white))
),
],
),
body: new Center(
child: new Text(
e,
style: new TextStyle(fontSize: 32.0),
),
)
);
}
}
发布于 2018-09-07 02:49:21
您需要在拥有新用户后调用setState()
。
在您的代码中,您创建了Future<String> email
,但无法利用最终的user.email
计算。
我建议创建一个非最终变量来保存FirebaseUser
,然后在State
的initState()
方法中触发对此的请求。
FirebaseUser currentUser; // not final
我们的目标是最终能够在接收到FirebaseUser之后调用setState()
(因为这是异步的)。
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() { // call setState to rebuild the view
this.currentUser = user;
});
});
需要注意的重要一点是,您必须为currentUser
的所有可能状态构建UI,这些状态包括:
null
(在调用completes)因此,您需要确保使用类似于以下逻辑的逻辑处理null
案例:
String _email() {
if (currentUser != null) {
return currentUser.email;
} else {
return "no current user";
}
}
下面是一个改编自你的代码的例子:
class _HomePageState extends State<HomePage> {
FirebaseUser currentUser;
@override
void initState() {
super.initState();
_loadCurrentUser();
}
void _loadCurrentUser() {
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() { // call setState to rebuild the view
this.currentUser = user;
});
});
}
String _email() {
if (currentUser != null) {
return currentUser.email;
} else {
return "no current user";
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.black,
title: Text('userEmail'),
actions: <Widget>[
new FlatButton(
onPressed: _signOut,
child: new Text('logout',
style: new TextStyle(fontSize: 17.0, color: Colors.white))),
],
),
body: new Center(
child: new Text(
_email(),
style: new TextStyle(fontSize: 32.0),
),
));
}
}
https://stackoverflow.com/questions/52210184
复制相似问题