用户已使用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),
),
)
);
}
}
拥有新用户后,您需要调用setState()
。
在您的代码中,您创建Future<String> email
但无法利用最终的user.email
评估。
我建议创建一个非final变量来保存你的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
(在通话结束前)因此,您需要确保使用类似于以下的逻辑来处理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),
),
));
}
}