我面临以下问题:我正在列表磁贴中的字幕中显示用户的Google帐户的用户名,但是如果用户未先登录,我使用的代码将显示错误,因此我可以编辑此代码以显示用户未登录或注销时尚未登录。另外,如果用户登录或更改了帐户,则如何显示Google帐户的用户名,这是代码:
subtitle: new FutureBuilder<FirebaseUser>(
future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context,AsyncSnapshot<FirebaseUser> snapshot){
if (snapshot.connectionState == ConnectionState.waiting) {
return new Text(snapshot.data.displayName);
}
else {
return new Text('you are not logged in');
}
},
答案 0 :(得分:1)
您可以简单地将snapshot.connectionState == ConnectionState.waiting
替换为is the equivalent of snpashot.data != null
的snapshot.hasData
。但是,即使仍在等待,它也会显示'you are not logged in'
。我添加了'loading'
Text
以便等待:
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('loading');
} else if (!snapshot.hasData) {
return Text('you are not logged in');
} else {
return Text(snapshot.data.displayName);
}
}
之所以有效,是因为currentUser()
returns null
if there is no current user。
您当前正在使用currentUser()
,它不会随着身份验证更改而更新。您可以使用onAuthStateChanged
,该流将更新 每 时间,并始终为您提供最新的用户。为此,您必须迁移到StreamBuilder
:
subtitle: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('loading');
} else if (!snapshot.hasData) {
return Text('you are not logged in');
} else {
return Text(snapshot.data.displayName);
}
},
)