Firebase for Flutter: Setting Up

Β·

8 min read

Hello awesome devs, In this blog we are going to learn how to connect our Flutter apps to Firebase.

Firebase is a fully managed backend service. It consists of a bunch of cool services like:

  • Data Storage/Database

  • File Storage

  • Authentication

  • Push notification Service

  • Analytics and more...

Prerequisites

I'm assuming you are familiar with building Flutter apps.

Introduction

We are going to learn how to connect our flutter application to Cloud Firestore. And perform a simple read as a bonusπŸ˜‰πŸ˜‰.

1.) Create a new flutter app

Follow the getting started guide to learn how to create a new flutter app.

2.) Update Dependencies

In your pubspec.yaml file, add dependecy for cloud_firestore and firebase_core then install them.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  firebase_core: ^0.5.0
  cloud_firestore: ^0.14.0+2

If you're developing your application on Android, we'll need to bump its minSdkVersion to 21 for the app to keep compiling after you add the cloud_firestore dependency. In your android/app/build.gradle file, update the minSdk:

    defaultConfig {
// note that our app id will vary, based on how you named your application
        applicationId "com.example.flutter_firebase_demo"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

3.) Update UI

In your main.dart file, update the existing code with the code below:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase for Flutter Demo',
      home: Scaffold(
        body: ListView.builder(
          itemBuilder: (ctx, idx) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text('This is a text'),
            );
          },
          itemCount: 10,
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {},
        ),
      ),
    );
  }
}

Run your app to ensure everything is working fine. Basically what our UI displays is a list of 10 text widgets.

4.) Create a firebase project

  • If you have a firebase account sign in to it and head over to the console.
  • In the firebase console, click on add project.
  • enter a name for your Firebase project and click "Continue".
  • since we won't be using analytics, you can disable it for this demo, then click on "Create Project"
  • once done, click on "Continue"

5.) Platform-specific Firebase configuration

Since I'm working on a windows machine, the following instructions will help you configure your android app to use firebase. However, if you are building for ioS use this site to configure.

If your app is still running at this point, stop the application.

  • In the Project Overview , click the android icon to add an android app.
  • Head over to your android/app/build.gradle file and copy the applicationId. Use the appId as the android package name
  • Click on "Register App"
  • Download the Config file and place it in you android/app folder.
  • Back to the console, Follow the instructions to add the firebase SDK to your project-level and app-level build.gradle file. DON'T SKIP THIS STEP
  • Once done click on "Next" then "Continue to Console"

Run your app a fresh from start to ensure everything is still working fine. You might need to close your project and reopen.

5.) Create your Cloud Firestore Database

  • In your console, on the left nav, click on "Cloud Firestore" then "Create Database"
  • Ensure "start in test mode" is selected and click on "next" then "enable".
  • In your database, click on "start a new collection" - data in Cloud firestore is structured in collections which is made up of documents. Nesting can be done as required.

image.png

  • Name your collection and click on next

image.png

  • Add a document, select auto-id to automatically generate an id. Add a field and give it a value(if you're familiar with OOP, this should make sense). You can select the type form the drop down

image.png

  • Add two more documents by clicking on add documents

image.png

6.) Connect your Flutter app to Cloud Firestore

In your main.dart file update your code as shown:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

In the above code, we import the firebase_core dependency and initialize our firebase app.

If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. (πŸ˜‰copy pasted from an error I encountered).

.6) Test if your app is successfully connected to your database

  • To test, update the onPressed function of your fab
floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            FirebaseFirestore.instance.collection('places').snapshots().listen((
                data) {
              print(' length : ${data.docs.length}');
            });
          },
        ),

if length : 3 is printed in your console, your flutter app is successfully connected to your database πŸŽ‰πŸŽ‰πŸŽ‰. Pretty neat, right?!

BONUS

As promised let's do a simple read. Update your MyApp Widgets as shown, run your app and see the magic. πŸ˜‰πŸ’™πŸŽ‰

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase for Flutter Demo',
      home: Scaffold(
        body: StreamBuilder(
          stream:  FirebaseFirestore.instance.collection('places').snapshots(),
          builder: ( BuildContext ctx, AsyncSnapshot<QuerySnapshot> snapshot){
            if(snapshot.connectionState == ConnectionState.waiting){
              return Center(child: CircularProgressIndicator(),);
            }
            final documents = snapshot.data.docs;
            return ListView.builder(
              itemBuilder: (ctx, idx) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(documents[idx].data()['city']),
                );
              },
              itemCount: documents.length,
            );
          },
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {

          },
        ),
      ),
    );
  }
}

Hope this helps. Happy coding!

Like my work? Buy me a coffee