Home > Mobile >  use StreamBuilder with collectionrefrence as snapshot in flutter
use StreamBuilder with collectionrefrence as snapshot in flutter

Time:03-02

I'm new to flutter and I'm trying to retrieve a list of categories from the firebase cloud firestore into my flutter application using StreamBuilder. Im using flutter 2.8.0 and cloud_firestore: ^3.1.7 this my firestore documents: categories collection here is my code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:harfanah/shared/loading.dart';

class categoriesMod extends StatefulWidget {
  const categoriesMod({ Key? key }) : super(key: key);

  @override
  _categoriesModState createState() => _categoriesModState();
}

class _categoriesModState extends State<categoriesMod> {
  @override
  Widget build(BuildContext context) {
    return Scaffold (
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('categories').snapshots(),
        builder: (context, snapshot) {
          if(!snapshot.hasData) {
            return loading();
          }
          return ListView.builder(
            itemCount: ,
            itemBuilder: ,
          );
        },
      ),
    );
  }
}

I'm really confused about how can I use ItemCount and ItemBuilder. I found many many solution that say i should use something like this: itemCount: snapshot.data.documents.length but it does not work. data does not even have any attributes other than these: data attributes

CodePudding user response:

You need to specify the type of the StreamBuilder then you can use the properties/methods available in the class QuerySnapshot:

class _categoriesModState extends State<categoriesMod> {
  @override
  Widget build(BuildContext context) {
    return Scaffold (
      body: StreamBuilder<QuerySnapshot<Map<String,dynamic>>>(
        stream: FirebaseFirestore.instance.collection('categories').snapshots(),
        builder: (context, snapshot) {
          if(!snapshot.hasData) {
             return loading();
          }
          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context,index){
              return ListTile(
                title: snapshot.data!.docs[index].data()["code"],
                leading: snapshot.data!.docs[index].data()["name"],
              );
            } ,
          );
        },
      ),
    );
  }
}
  • Related