如何使用Flutter在Firestore中访问特定配方的documentId?

时间:2018-08-28 18:40:58

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

  @override
  Widget build(BuildContext context) {
return new Scaffold(
  appBar: new AppBar(
    title: new Text(
      "Comments",
      style: TextStyle(color: Colors.white),
    ),
    backgroundColor: primaryColor,
  ),
  body: StreamBuilder(
    stream: Firestore.instance.collection('recipes').document('MXYt6fLDt5F4I1XJen31').collection('comments').snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
      if(!snapshot.hasData) return CircularProgressIndicator();
      return FirestoreListView( documents: snapshot.data.documents);
    },
  ),
);
}
}

class FirestoreListView extends StatelessWidget {
 final List<DocumentSnapshot> documents;

 FirestoreListView({this.documents});

 @override
 Widget build(BuildContext context) {
  return ListView.builder(
  itemCount: documents.length,
  itemBuilder: (BuildContext context, int index){
    String message = documents[index].data['message'].toString();

    return ListTile(
      title: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.0),
          border: Border.all(color: Colors.black),
        ),
        padding: EdgeInsets.all(5.0),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(message),
            ),
          ]
        ),
      )
    );

  },
);

} }

Firestore.instance.collection('recipes')。文档('MXYt6fLDt5F4I1XJen31') .collection('comments')。snapshots()

在这里您可以看到,我正在使用其对应的ID访问一个已经存在的配方。我想转到详细信息页面,然后留下只针对该食谱显示的评论。所以我需要访问该UNIC ID。

1 个答案:

答案 0 :(得分:0)

您可以使用forEach方法尝试以下操作:

@override
  Widget build(BuildContext context) {
    return Scaffold(
     body: Container(
        child: Center(
          child: StreamBuilder(
            stream: Firestore.....your_path....collection('comments').snapshots(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<DocumentSnapshot> documentSnapshotsList =
                    snapshot.data.documents;

                List<Recipe> recipesList = [];

                documentSnapshotsList.forEach((documentSnapshot) {
                  Recipe recipe = Recipe(
                    id: documentSnapshot["recipe_id"],
                    name: documentSnapshot["recipe_name"],
                    image: documentSnapshot["recipe_image_url"],
                  );

                  recipesList.add(recipe);
                });

                return FirestoreListView(recipesList);
              } else if (snapshot.hasError)
                return Text("Error");
              else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }