从Firebase获取用户数据

时间:2020-07-15 18:31:06

标签: firebase flutter dart google-cloud-firestore firebase-authentication

我正在尝试从用户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();
                  },
                ),
              ),

输出如下:

enter image description here

enter image description here

1 个答案:

答案 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食谱:

https://flutter.dev/docs/cookbook