将快照数据传递给类时出错

时间:2020-03-10 20:06:08

标签: flutter dart

我正在尝试将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")

1 个答案:

答案 0 :(得分:1)

通过致电

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

您正在检索一个列表,而不仅仅是一个文档。所以您想要的是这样的:

Text("${doucment.data.documents[index]['name']}",
                    style: TextStyle(fontWeight: FontWeight.bold))
相关问题