- Create a new dart file in lib : recipes.dart
- Create a stateless widget inside the above file
class Recipes extends StatelessWidget {}
- Return a Scaffold with an AppBar from the build function
- Add a StreamBuilder to the body of the Scaffold
StreamBuilder(stream: ,builder: (context,snapshot){} )
- 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){} ) }
- 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']),
);
},
);
}),
);
}
}