首页 > 解决方案 > 如何从firebase而不是硬代码中提取值

问题描述

我正在颤振中构建一个个人资料页面,我想知道用从 Firestore 中提取的值简单地替换硬编码值的最佳方法是什么。有没有人对如何最好地做到这一点有任何建议?

没有发现教程有用。

我正在尝试用从 Firestore 中提取的值替换以下数值。

new Row(
                  children: <Widget>[
                    rowCell(343, 'POSTS'),
                    rowCell(673826, 'FOLLOWERS'),
                    rowCell(275, 'FOLLOWING'),
                  ],),

标签: androidfirebaseandroid-studioflutterandroid-emulator

解决方案


理想情况下,您希望将用户 ID 传递给返回配置文件的小部件。例如

    class ProfileWidget extends StatelessWidget {

    final String userId;
    ProfileWidget (this.userId);
          @override
      Widget build(BuildContext context) {
   return StreamBuilder<DocumentSnapshot>(
            stream: Firestore.instance
                .collection('users')
                .document(userId)
                .snapshots(),
            builder: (context, snapshot) {
              User user = User.fromSnapshot(snapshot.data);
              return Row(
                      children: <Widget>[
                        rowCell(user.posts, 'POSTS'),
                        rowCell(user.followers, 'FOLLOWERS'),
                        rowCell(user.following, 'FOLLOWING'),
                      ],),

                      },
          );},}

现在用户类:

class User{
  final int following;
  final int posts;
  final int followers;
  final DocumentReference reference;

  User.fromMap(Map<String, dynamic> map, {this.reference})
      : following = map['following'],
        posts = map['posts'],
        followers= map['followers'];

  User.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);
}

推荐阅读