带有Flutter和Firestore的GridView

时间:2019-02-07 21:32:47

标签: flutter google-cloud-firestore

我正在尝试从云Firestore记录中创建一个简单的GridView。我已经看了很多视频教程,但是都没有成功。这是代码:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class EventList extends StatefulWidget {
 @override
 EventListState createState() => new EventListState();
}

class EventListState extends State<EventList> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('events_flutter').snapshots(),
  builder: (BuildContext context, DocumentSnapshot snapshot) {
    if (!snapshot.hasData) {
      return Center(child: const Text('Loading events...'));
    }
    return GridView.builder(
      gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        return Text(snapshot['event_name']);
      },
      itemCount: snapshot.data.documents.length,
    );
  },
);}}

这是当悬停在“ builder:(BuildContext上下文,DocumentSnapshot快照)”上时的错误消息。 有人可以帮助我了解发生了什么事吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

您应该将snapshot的类型从DocumentSnapshot替换为AsyncSnapshot

...

builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (!snapshot.hasData) {
        return Center(child: const Text('Loading events...'));
    }

    ...

而且,您可能要替换此行:

return Text(snapshot['event_name']);

对此:

return Text(snapshot.data.documents[index]['event_name']);

答案 1 :(得分:0)

您collection()。snapshot()返回QuerySnapshot,因此您必须像这样将DocumentSnapshot更改为QuerySnapshot:

std::main_thread