我正在尝试从用户uid中获取用户数据,并将其用于文本窗口小部件。我应该创建getCurrentUser方法来获取数据吗?我曾尝试使用querysnapshots,但它什么也没做。这是代码:
Expanded(
child: Container(
margin: EdgeInsets.only(top: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Name'),
Text('Email@email.com'),
Text('+02112345678'),
],
),
),
),
这是更新内容:
Expanded(
child: Container(
margin: EdgeInsets.only(top: 10.0),
child: FutureBuilder(
future: getData(),
builder: (context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data['Full Name']),
Text(snapshot.data['Email Address']),
Text(snapshot.data['Phone Number']),
],
);
} else if (snapshot.connectionState ==
ConnectionState.none) {
return Text("No Data");
}
return CircularProgressIndicator();
},
),
),
输出如下:
答案 0 :(得分:1)
您需要使用FutureBuilder
小部件,首先创建一种获取用户的方法:
Future<DocumentSnapshot> getData() async {
FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
return await Firestore.instance
.collection("UserAccount").document(firebaseUser.uid).get();
}
然后在build
方法内:
FutureBuilder(
future: getData(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data["name"]),
Text(snapshot.data["email"]),
Text(snapshot.data["number"]),
],
),
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
),
在上面的代码中,由于FutureBuilder
是异步的,因此我们使用get()
,然后在ConnectionState.done
内使用snapshot.data
获取数据。
最好阅读文档,检查所有flutter食谱: