Reputation: 1161
User already login to the app by using firebase email login. How to make the appbar title to be the current user email?
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),
),
)
);
}
}
Upvotes: 0
Views: 2023
Reputation: 17799
You need to call setState()
after you have the new user.
In your code, you create the Future<String> email
but aren't able to capitalize on the eventual user.email
evaluation.
I recommend creating a non-final variable to hold your FirebaseUser
and then trigger the request for this in the State
's initState()
method.
FirebaseUser currentUser; // not final
The goal is to eventually be able to call setState()
after receiving the FirebaseUser (since that's asynchronous).
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() { // call setState to rebuild the view
this.currentUser = user;
});
});
An important thing to note is that you have to build your UI for all the possible states of currentUser
which are:
null
(before the call completes)So you need to make sure you handle the null
case with logic similar to:
String _email() {
if (currentUser != null) {
return currentUser.email;
} else {
return "no current user";
}
}
Below is an example adapted from your code:
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),
),
));
}
}
Upvotes: 2