我正在尝试将Snapshot数据传递给新类,但出现错误(请参见下文)。我尝试添加Snapshot[index],但再次出现错误,但我不知道为什么。
我正在使用 cloud_firestore

代码是:

Container(
                height: 171,
                child: StreamBuilder<QuerySnapshot>(
                  stream: Firestore.instance.collection('offers').snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError) return new Text('${snapshot.error}');
                    switch (snapshot.connectionState) {
                      case ConnectionState.waiting:
                        return new Center(child: new CircularProgressIndicator());
                      default:
                        return new SingleItem(doucment: snapshot,);
                    }
                  },
                ),
              )

SingleItem类是
class SingleItem extends StatelessWidget {
  final doucment;
  SingleItem({this.doucment});
  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Container(
        width: 251,
        margin: EdgeInsets.symmetric(vertical: 5.0, horizontal: 15.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15.0),
          boxShadow: [
            BoxShadow(color: Colors.grey[300], blurRadius: 3.0),
          ],
        ),
        child: Stack(
          children: <Widget>[
            Positioned(
              bottom: 20,
              right: 120,
              child: Container(
                child: Image.asset(
                  "assets/camera.png",
                  width: 121,
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(15.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "${doucment.data['name']}",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Text(
                    "\$ 39.99",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Spacer(),
                  Text(
                    "Ends in 02:00:25",
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

错误控制台为
Class 'AsyncSnapshot<QuerySnapshot>' has no instance method '[]'.
Receiver: Instance of 'AsyncSnapshot<QuerySnapshot>'
Tried calling: []("name")

最佳答案

通过致电

Firestore.instance.collection('offers').snapshots()

您正在检索列表,而不仅仅是单个文档。所以您想要的是这样的:
Text("${doucment.data.documents[index]['name']}",
                    style: TextStyle(fontWeight: FontWeight.bold))

10-06 01:24