6.0 Introduction

Firestore is a flexible, scalable NoSQL cloud database and allows developers to store and sync data in real-time across all clients with strong user-based security.

Firestore is designed to make it easy to build applications that keep user data in sync across devices and provide offline support.

Data is organised into collections and documents, where each document can contain subcollections and fields of various data types.

Firestore supports powerful querying, real-time updates, and seamless integration with other Firebase services, making it a popular choice for building dynamic and scalable applications.

6.1 Collections and Documents

Collections are organisational containers for storing documents within the Firestore database. Each collection holds multiple documents, with each document containing key-value pairs and potentially other sub collections. Firestore containers support real-time updates which synchronises data accross clients and users.

Lets look at an example.

In our reddit clone app, we want users to be able to create posts and communities. This could look like a collection called posts, with each document relating to information from a post itself.

Untitled

6.2 Reading from Firestore

First things first, we want our app to be able to read what posts there are in Firestore and display these to the user. This functionality is something we want to the Feed Page. Picking up from where we left off in the previous section, lets extend pages/feed.dart to fetch data from Firestore.

  1. Import the required packages
// pages/feed.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
  1. Just like with authentication, we are going to be using Streams to get real time data from our database.
// pages/feed.dart

class FeedPage extends StatelessWidget {
  FeedPage({super.key});

	// Define this stream before the build statement
  final Stream<QuerySnapshot> collectionStream = FirebaseFirestore.instance
      .collection('posts') // Choose which collection we want to read
      .orderBy("date", descending: true) // OPTIONAL: Set an order
      .snapshots(); // Get notified of any changes to the collection

  @override
  Widget build(BuildContext context) {
  ...