15.9 Reading data from Cloud Firestore
flutter pub add firebase_core
flutter pub add cloud_firestore
Example: Firebase Essentials II
import 'package:cloud_firestore/cloud_firestore.dart' ;
import 'package:firebase_core/firebase_core.dart' ;
import 'package:flutter/foundation.dart' ;
import 'package:flutter/material.dart' ;
import 'firebase_options.dart' ;
void main () async {
await Firebase .initializeApp (
options: DefaultFirebaseOptions .currentPlatform,
);
if (kDebugMode) {
try {
FirebaseFirestore .instance.useFirestoreEmulator ('localhost' , 8080 );
} catch (e) {
// ignore: avoid_print
print (e);
}
}
runApp (const MyApp ());
}
class MyApp extends StatelessWidget {
const MyApp ({Key ? key}) : super (key: key);
// This widget is the root of your application.
@override
Widget build (BuildContext context) {
return MaterialApp (
title: 'Firestore Demo' ,
theme: ThemeData (
primarySwatch: Colors .blue,
),
home: const MyHomePage (title: 'Flutter Firestore Database: Read' ),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage ({Key ? key, required this .title}) : super (key: key);
final String title;
@override
State <MyHomePage > createState () => _MyHomePageState ();
}
class _MyHomePageState extends State <MyHomePage > {
@override
Widget build (BuildContext context) => Scaffold (
appBar: AppBar (
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our AppBar title.
title: Text (widget.title),
),
body: StreamBuilder <List <Team >>(
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text ('Unable to read Cloud Firestore' );
} else if (snapshot.hasData) {
final dbteams = snapshot.data! ;
return ListView (children: dbteams.map (buildTeam).toList ());
} else {
return const Center (
child: CircularProgressIndicator (),
);
}
},
stream: readTeams (),
),
);
Widget buildTeam (Team team) => ListTile (
leading: const CircleAvatar (child: Text ('Prem' )),
title: Text (team.name),
subtitle: Text (team.location),
);
Future createTeam ({required String name, required String location}) async {
// Write to the Cloud Firestore database
final docTeam = FirebaseFirestore .instance.collection ('Teams' ).doc ();
final teamJSON = {
'name' : name,
'location' : location,
};
// Create the document and write data
await docTeam.set (teamJSON);
// Add: import 'package:flutter/foundation.dart';
// Production Debug statement
if (kDebugMode) {
print ("Database Write!" );
}
}
Stream <List <Team >> readTeams () => FirebaseFirestore .instance
.collection ('teams' )
.snapshots ()
.map ((snapshot) =>
snapshot.docs.map ((doc) => Team .fromJson (doc.data ())).toList ());
}
class Team {
// String id;
final String name;
final String location;
Team ({
// this.id = '',
required this .name,
required this .location,
});
Map <String , dynamic > toJson () => {
// 'id': id,
'name' : name,
'location' : location,
};
static Team fromJson (Map <String , dynamic > json) => Team (
// id: json['id'],
name: json['name' ],
location: json['location' ]);
}
if (kDebugMode) {
try {
FirebaseFirestore .instance.useFirestoreEmulator ('localhost' , 8080 );
} catch (e) {
print (e);
}
}