Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView with Flutter and Firestore

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.

like image 911
Juca Esmanhoto Avatar asked May 12 '26 15:05

Juca Esmanhoto


1 Answers

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']);
like image 92
Jerome Escalante Avatar answered May 15 '26 03:05

Jerome Escalante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!