【问题标题】:create the list from the query collection of documents from firestore从 firestore 中的文档查询集合创建列表
【发布时间】:2021-05-05 07:14:02
【问题描述】:

我成功地从 Flutter 应用程序中的 firestore 集合中获取文档并创建了一个列表视图构建器。 除此之外,我想创建一个特定字段的列表,该列表对集合中的所有文档都是通用的。

例如,每个文档都有 username 的公共字段,在从 firestore 集合中获取所有文档后,我想创建一个用户名列表 List usernames = [];,我可以在其中添加集合中的所有用户名。

Query query2 =   FirebaseFirestore.instance
        .collection('users');


StreamBuilder<QuerySnapshot>(
                 stream: query2.snapshots(),

              builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot) {

                if (snapshot.hasError) {
                  return Text('Something went wrong');
                }

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Text("Loading");
                }

                return ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index){

                    return ListTile(title:Text(snapshot.data.docs[index]['username'] ?? "",
                                    subtitle:Text(snapshot.data.docs[index]['email'] ?? ""
                  ),);
                  });
                }
              )

上面的代码运行良好,我想创建一个单独的列表用于用户名List usernames = [];

我该怎么做?请指教

【问题讨论】:

    标签: list firebase flutter google-cloud-firestore flutter-listview


    【解决方案1】:
    var usernames = snapshot.data.docs.map((e) => e['username']);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      查询 query2 = FirebaseFirestore.instance .collection('users').where("username",isNull: false );

      流生成器( 流:query2.snapshots(),

                builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot) {
      
                  if (snapshot.hasError) {
                    return Text('Something went wrong');
                  }
      
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Text("Loading");
                  }
      
                  return ListView.builder(
                    itemCount: snapshot.data.docs.length,
                    itemBuilder: (context, index){
      
                      return ListTile(title:Text(snapshot.data.docs[index]['username'] ?? "",
                                      subtitle:Text(snapshot.data.docs[index]['email'] ?? ""
                    ),);
                    });
                  }
                )
      

      这基本上是检查整个集合并返回username 不为空的数据。

      【讨论】:

        猜你喜欢
        • 2020-07-24
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        • 2018-05-09
        • 2021-04-08
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        相关资源
        最近更新 更多