GridView with Flutter and Firestore

∥☆過路亽.° 提交于 2020-12-13 05:45:23

问题


I`m trying to make a simple GridView from a cloud firestore record. I've followed a lot of video tutorials but without success. Here's the code:

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,
    );
  },
);}}

And this is the error message when hovering on "builder: (BuildContext context, DocumentSnapshot snapshot)". Could anybody help me understand what is going on?

Thanks a lot.


回答1:


You should replace the type of your snapshot from DocumentSnapshot to AsyncSnapshot.

...

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

    ...

And also, you might want to replace this line:

return Text(snapshot['event_name']);

to this:

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



回答2:


You collection().snapshot() returns QuerySnapshot, so you would have to change DocumentSnapshot to QuerySnapshot like this:

class EventListState extends State<EventList> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('events_flutter').snapshots(),
  builder: (BuildContext context, QuerySnapshot 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,
    );
  },
);}}


来源:https://stackoverflow.com/questions/54582633/gridview-with-flutter-and-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!