将Firebase Firestore Listview数据显示为列表Flutter

时间:2018-12-01 17:19:22

标签: firebase dart flutter google-cloud-firestore

我目前能够显示一个列表视图,其中填充了Firestore数据库中的数据。我当前的问题是,我想使其成为可废止的,所以我需要能够使用以下功能:

  setState(() {
    items.removeAt(index);
  });

现在,我阅读了如何生成列表的信息,但是没有一个示例像我使用的那样提及Firebase Streambuilder。所以我只是想知道是否有可能将数据放入列表中?如果不是,是否还有其他方法可以取消Firestore Listview?这是我当前获取数据的方式:

Container(
          child: StreamBuilder(
            stream: Firestore.instance.collection('users').snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                  ),
                );
              } else {
                return ListView.builder(
                  scrollDirection: Axis.vertical,
                  padding: EdgeInsets.all(10.0),
                  itemBuilder: (context, index) => buildItem(context, snapshot.data.documents[index]),
                  itemCount: snapshot.data.documents.length,
                );
              }
            },
          ),
        ),

在此先感谢您的帮助。

Builditem看起来像这样:

  Widget buildItem(BuildContext context, DocumentSnapshot document) {
if (document['id'] == currentUserId || document['gender'] == null) {
  return Container();
}
if (currentUserPreference == 'male' && currentUserGender == 'male') {
  return showGayMales(document);
}

ShowGayMales方法如下:

 Widget showGayMales(DocumentSnapshot document) {      
   if (document['id'] == currentUserId || document['id'] == nopeId || ) {
     return Container();
   } else {
     return Container(
        child: Slidable(
          delegate: new SlidableScrollDelegate(),
          actionExtentRatio: 0.3,
        child: Card(
          child: Padding(
          padding:EdgeInsets.fromLTRB(20.0, 10.0, 25.0, 10.0),
          child: Row(
            children: <Widget>[
              Material(
                color: Colors.transparent,
                child: Icon(
                  FontAwesomeIcons.male,
                  color: textColor,
                ),
              ),
              new Flexible(
                child: Container(
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          child: Text(
                      '${document['aboutMe']}',
                            style: TextStyle(color: textColor, fontSize: 30.0),
                        ),
                        alignment: Alignment.centerLeft,
                        margin: new EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
                      ),
                      new Container(
                        child: Row(
                          children: <Widget>[
                            Text(
                            '-'+'${document['nickname'] ?? 'Not available'}',
                            style: TextStyle(color: textColor, fontSize: 15.0, fontWeight: FontWeight.bold),
                            ),
                            Text(
                              ','+' ${document['age'] ?? ''}'
                            )
                          ],
                        ),
                        alignment: Alignment.centerLeft,
                        margin: new EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
                      )
                    ],
                  ),
                  margin: EdgeInsets.only(left: 20.0),
                ),
              ),
            ],
          ),
          ),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
          ),
            actions: <Widget>[
             new IconSlideAction(
             caption: 'Not interested!',
             color: errorColor,
             icon: Icons.clear,
             onTap: () => notinterested('${document['id']}'),
             ),
            ],
            secondaryActions: <Widget>[
              new IconSlideAction(
              caption: "Interested!",
                color: primaryColor,
              icon: Icons.check,
              onTap: () => interested('${document['nickname']}', '${document['id']}', '${document['gender']}', '${document['aboutMe']}', '${document['age']}', '${document['preference']}'),
              ),
            ],
        ),
        margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
      );
   }
  }

1 个答案:

答案 0 :(得分:0)

您可以通过先将 Firestore 数据映射到对象来获取 Firestore 数据并将其添加到列表中。

List<Users> userList;
Future<void> getUsers() async {
  userList = [];
  var collection = FirebaseFirestore.instance.collection('users');
  collection.get().then((value) {
    value.docs.forEach((users) {
      debugPrint('get Users ${users.data()}');
      setState(() {
        // Map users.data to your User object and add it to the List
        userList.add(User(User.setUserDetails(users.data()))); 
      });
    });
  });
}

// Let's say this is User object
class User {
  var username;

  User(User doc) {
    this.username = doc.getUsername();
  }

  getUsername() => username;

  // fetch name using Firestore field name
  User.setUserDetails(Map<dynamic, dynamic> doc)
      : username = doc['name']; 
}