Display list of items from Cloud Firestore(Firebase)

  1. Create a new dart file in lib : recipes.dart
  2. Create a stateless widget inside the above file
    class Recipes extends StatelessWidget {} 
  3. Return a Scaffold with an AppBar from the build function
  4. Add a StreamBuilder to the body of the Scaffold
    StreamBuilder(stream: ,builder: (context,snapshot){} ) 
  5. Provide the reference of the firestore Collection named ‘Recipes’ to the stream property
    CollectionReference recipes = FirebaseFirestore.instance.collection('Recipes');   @override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(),       body: StreamBuilder(           stream: recipes.snapshots(),           builder: (context,snapshot){} ) }
  6. Implement the builder function
    • Check if there is an error
    • Display a progress indicator if the connection state is waiting
    • Create a ListView with the items of the snapshot.data
      builder: (context,snapshot){             if (snapshot.hasError) {               return Text('Something went wrong');             }             if (snapshot.connectionState == ConnectionState.waiting) {               return Text("Loading");             }             return ListView.builder(               itemCount:snapshot.data.documents.length,               itemBuilder: (context,index){                 return ListTile(                   title: Text(snapshot.data.documents[index]['title']),                   subtitle: Text(snapshot.data.documents[index]['desc']),                 );               },             );           }),

Complete Code (recipes.dart)

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

class Recipes extends StatelessWidget {

  CollectionReference recipes = FirebaseFirestore.instance.collection('Recipes');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: StreamBuilder(
          stream: recipes.snapshots(),
          builder: (context,snapshot){
            if (snapshot.hasError) {
              return Text('Something went wrong');
            }

            if (snapshot.connectionState == ConnectionState.waiting) {
              return Text("Loading");
            }

            return ListView.builder(
              itemCount:snapshot.data.documents.length,
              itemBuilder: (context,index){
                return ListTile(
                  title: Text(snapshot.data.documents[index]['title']),
                  subtitle: Text(snapshot.data.documents[index]['desc']),
                );
              },
            );
          }),
    );
  }
}

Leave a Reply

Your email address will not be published.