Before using a Firestore database you need to create one. So, let’s get back to the Firebase console,
On the left side of the Firebase Project Overview page, click on the Firestore Database link. Here, under the Cloud Firestore pane, click on the Create Database button.
In the Create database page, choose Start in test mode. This is because at this time we want to allow access to data without authentication. Later on, we’ll set some rules, but for now this is enough.
Click Next. You’ll be asked to choose among the locations of the Cloud Firestore. Here just choose a location close to you and your users. As I live in Europe, I’ll choose one of the europe-west options. Finally, click Done.
After a few seconds, you’ll have your Cloud Firestore database, and you’re ready to use it in your app. Let’s get back to the Flutter project.
As usual, you need to import the Flutterfire plugin that allows using the Firestore database service. As you can see, the plugin is called cloud_firestore. In the terminal, type
flutter pub get cloud_firestore.
Next, in the data folder of the app, create a new file, called firebase_helper.dart. In the new file, import the cloud_firestore.dart file: this is everything you need to access your database.
import 'package:cloud_firestore/cloud_firestore.dart';
Here let’s create a class, called FirebaseHelper. At the top of the class, we want to add two fields: the first is a FirebaseFirestore object, called firestore. Let’s mark it late, as we’ll set it in the constructor.
This is an object that allows retrieving the Firestore instance from Flutter. Next, we’ll create a late CollectionReference, called activities: a CollectionReference, as the name implies, is the way you reach a Collection within your Firestore Database.
Next, let’s create an unnamed constructor. Here let’s set the two fields: firestore will just take a FirebaseFirestore instance. This is all that’s required to access firestore.
And activities will call the collection method from our firestore instance, and pass “activities” as this is the name we want to give to our collection. Note that we haven’t created any collection in the database yet, but this is not necessary: this will be created automatically when we add the first document to this collection.
late FirebaseFirestore firestore;
late CollectionReference activities;
FirebaseHelper() {
firestore = FirebaseFirestore.instance;
activities = firestore.collection('activities');
}
Great, you have now created a Firestore database and connected your project to the FIrestore instance. In the next few lessons, we’ll read and write data to the database.