如何从小部件中的Firestore检索数据?

时间:2019-03-19 11:56:57

标签: dart flutter google-cloud-firestore

在我的用户集合中,存储了photoURL,name之类的字段。 我想在我的小部件中显示此字段。

这是我获取当前用户的代码。

  Future<void> _getUserDoc() async {
    final FirebaseAuth _auth = FirebaseAuth.instance;
    final Firestore _firestore = Firestore.instance;

    FirebaseUser user = await _auth.currentUser();
    setState(() {
      userRef = _firestore.collection('users').document(user.uid);
    });
  }

我不知道如何获取数据字段。 这是我的小部件名称。

                  Padding(
                    padding:
                        const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
                    child: Text(
                      'Richie',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0),
                    ),
                  ),

我想在文本窗口小部件中显示 Richie ,而不是Firestore中的用户名。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用FutureBuilder来显示用户名,但是还需要获得当前用户,因此,如果您在其他地方没有获得当前用户,则可以使用嵌套的FutureBuilder s

您可以使用connectionState属性检查该将来的当前状态,并在connectionState等待时显示CircularProgressIndicator()

Widget DisplayUserName() {
  return FutureBuilder(
    future: FirebaseAuth.instance.currentUser(),
    builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return Text('Press button to start.');
        case ConnectionState.active:
        case ConnectionState.waiting:
          return Text('Awaiting result...');
        case ConnectionState.done:
          if (snapshot.hasError)
            return Text('Error: ${snapshot.error}');
          return FutureBuilder(
            future: Firestore.instance.collection('users').document(snapshot.data.uid).get(),
            builder: (BuildContext context,
                AsyncSnapshot<DocumentSnapshot> user) {
              switch (user.connectionState) {
                case ConnectionState.none:
                  return Text('Press button to start.');
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return CircularProgressIndicator();
                case ConnectionState.done:
                  if (user.hasError)
                    return Text('Error: ${user.error}');
                  return Padding(
                    padding:
                    const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
                    child: Text(
                      user.data['name'],// Im assuming in CloudFirestore your field name is name.
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0),
                    ),
                  );
              }
              return null; // unreachable
            },
          );
      }
      return null; // unreachable
    },
  );
}

如果您当前有全球用户

  Future<FirebaseUser> user;

  // you may get it in initState
  @override
  void initState() {
    user = FirebaseAuth.instance.currentUser();
    super.initState();
  }

这就足够了,

  return FutureBuilder(
    future: Firestore.instance.collection('users').document(user.uid).get(),
    builder: (BuildContext context,
        AsyncSnapshot<DocumentSnapshot> user) {
      switch (user.connectionState) {
        case ConnectionState.none:
          return Text('Press button to start.');
        case ConnectionState.active:
        case ConnectionState.waiting:
          return Text('Awaiting result...');
        case ConnectionState.done:
          if (user.hasError)
            return Text('Error: ${user.error}');
          return Padding(
            padding:
            const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
            child: Text(
              user.data['name'],
              style: TextStyle(
                  fontFamily: 'Montserrat',
                  fontWeight: FontWeight.bold,
                  fontSize: 17.0),
            ),
          );
      }
      return null; // unreachable
    },
  );