Docs
Set-up the Database

Set-up the Database

Config to connect your database with our templates.

The template interacts with a backend database via the db_client local package. The role of the package is to facilitate CRUD (Create, Read, Update, Delete) operations through the DbClient interface. Here's an overview of the package structure:

# The structure of the db_client
├── README.md
├── client
│   ├── lib
│   │   ├── client.dart
│   │   └── src
│   │       └── firebase_db_client.dart
│   └── pubspec.yaml
├── server
│   ├── lib
│   │   ├── server.dart
│   │   └── src
│   │       └── grpc_firebase_db_client.dart
│   └── pubspec.yaml
└── shared
    ├── lib
    │   ├── shared.dart
    │   └── src
    │       ├── db_client.dart
    │       ├── db_record.dart
    │       ├── fake_db_client.dart
    │       └── filter.dart
    └── pubspec.yaml

The DbClient interface provides methods to interact with the database, while, the DbRecord class acts as a standard data structure for returning the document's data. The DbRecord class contains two main properties:

  • ID: Represents the unique identifier of the retrieved document.
  • data: A dictionary (key-value pairs) of the document's contents.

The local package contains three implementations of the DbClient interface that are suitable for different scenarios:

  1. FakeDbClient
  2. FirebaseDbClient
  3. GrpcFirebaseDbClient

FakeDbClient

The FakeDbClient is utilized in the development flavor of the app, and it enables you to explore the app's UI without connecting to a live database. In practice, it gives you a simulated data environment to try the app before setting up the connection with your actual database.

The FakeDbClient utilizes an in-memory datastore. The sample data is stored within the _dataStore map, which organizes data as key-value pairs, and the template can read and write data to the in-memory storage.

final Map<String, List<Map<String, dynamic>>> _dataStore = {};

The FakeDbClient does not persist data across multiple session. In practice, during the app's initialization in the development flavor, the FakeDbClient is instantiated and populated with sample data.

# lib/main_development.dart
void main() async {
  unawaited(
    bootstrap(
      () async {
        WidgetsFlutterBinding.ensureInitialized();

        // Initialize the fake database client
        final dbClient = FakeDbClient();

        // Load sample product data into the fake database
        for (var product in Product.sampleProducts) {
          await dbClient.add(
            entity: 'products',
            data: product.toJson(),
          );
        }

        // Load sample category data into the fake database
        for (var category in Category.sampleCategories) {
          await dbClient.add(
            entity: 'categories',
            data: category.toJson(),
          );
        }

        // Additional data initialization can be added here
        ...
      }
    )
  );
}

FirebaseDbClient

The FirebaseDbClient is the production-ready implementation that integrates the template with a real Cloud Firestore database. It is the default option when you run the app in the production flavor.

Before you can use the FirebaseDbClient, there is some set-up required on your side.

Connect the App with Firebase

If you haven't already set-up Firebase during the authentication configuration, create a Firebase account and use flutterfire configure to integrate Firebase into your app. You can follow the official step-by-step docs

Initialize the Cloud Firestore Database

  1. Navigate Cloud Firestore: In your Firebase project, navigate to the Cloud Firestore section by selecting Build --> Firestore Database.
  2. Create the Database: Choose a location that suits your needs and create the database.
  3. Start in Test Mode: Initialize the database in test mode to allow unrestricted access during development.

Load Data into the Database

The template includes a data_loader package. It is a simple web app designed to import sample data from the core package into Firestore. This ensures that you have the initial data to work with in your template.

  1. Configure a Web App in Firebase: Within your Firebase project's General tab, add a new Web App.

Set-up Data Loader

  1. Set up the Data Loader: Use the credentials from the newly created web app to configure the data_loader as follows:
# packages/data_loader/lib/main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: const FirebaseOptions(
      # Replace the ... with your actual values. 
      apiKey: "...",
      authDomain: "...",
      projectId: "...",
      storageBucket: "...",
      messagingSenderId: "...",
      appId: "...",
    ),
  );

  runApp(const MyApp());
}
  1. Upload Data: Execute the main() function in the data_loader and verify that the data has been successfully uploaded to your Firestore project.

Note: You should complete these steps before implementing security rules in your Firestore database to avoid access issues.

GrpcFirebaseDbClient

The GrpcFirebaseDbClient is another production-ready implementation for integrating the template with Cloud Firestore. Unlike the FirebaseDbClient, which is designed for client-side use (e.g. from the Flutter app), the GrpcFirebaseDbClient works for server-side operations.

The two implementations are required due to compatibility issues with the packages used in these implementations:

  • Client-Side Implementation: The FirebaseDbClient utilizes the cloud_firestore package, which is specifically designed for the Flutter SDK and is not suitable for backend server environments.
  • Server-Side Implementation: For Dart-based backend environments, the GrpcFirebaseDbClient uses the firedart package to perform the same type of database operations from a server-side environment.

If your purchased template includes a backend server component, the following setup steps are necessary:

  1. Load Data into the Database: This step is identical to the one for the FirebaseDbClient. If you have already completed it, you can skip this part.
  2. Configure Your Backend Server: Go ahead and check the step-by-step docs related to the backend server setup.