Table of Contents
Introduction
Firebase is a Backend-as-a-Service — BaaS — that started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform.
Firebase frees developers to focus on crafting fantastic user experiences. You don’t need to manage servers. You don’t need to write APIs. Firebase is your server, your API and your datastore, all written so generically that you can modify it to suit most needs. Yeah, you’ll occasionally need to use other bits of the Google Cloud for your advanced applications. Firebase can’t be everything to everybody. But it gets pretty close.
Firebase, a comprehensive development platform provided by Google, offers a wide range of powerful tools and services for building mobile and web applications.
Prerequisites
-
Install your preferred editor or IDE.
- Set up a physical Apple/Android device or use a Simulator/Emulator to run your app.
- Make sure that your Flutter app targets the following platform versions or later:
- For Ios use iOS 11 or later version and make sure you have macOS 10.13 or later version’s system
- For Android use Targets API level 19 (KitKat) or higher, and uses Android 4.4 or higher/li>
-
Install Flutter for your specific operating system, including the following:
- Flutter SDK
- Supporting libraries
- Platform-specific software and SDKs
-
Sign into Firebase using your Google account.
-
If you are unaware about flutter or don't already have a Flutter app, you can complete the Get Started: Test Drive to create a new Flutter app using your preferred editor or IDE.
Creating a firebase project
Follow the steps below.
-
Navigate to firebase.google.com
-
Click Get Started.
- Login with your Google account.
- On the welcome screen, click Add project.
-
Click Create a project
-
Enter a name for your project and click Continue.
-
If you would like to track your app using Google Analytics, then make sure that the option is enabled before using the Continue button to proceed.
-
Choose or create a Google Analytics account and click on the Create Project button to finish creating the Firebase project.
-
Wait until firebase preparing your project. Then your project will ready to use.
-
Your project overview dashboard will look like as in below attached image:
Adding firebase to your flutter project
Step 1: Install the required command line tools
-
If you haven't already, install the Firebase CLI
- Log into Firebase using your Google account by running the following command: firebase login
- Install the FlutterFire CLI by running the following command from any directory: dart pub global activate flutterfire_cli
Step 2: Configure your apps to use Firebase
- Use the FlutterFire CLI to configure your Flutter apps to connect to Firebase.
- From your Flutter project directory, run the following command to start the app configuration workflow:
- your-flutter-proj$ flutterfire configure
What does this flutterfire configure workflow do?
The flutterfire configure workflow does the following:
- Asks you to select the platforms (iOS, Android, Web) supported in your Flutter app. For each selected platform, the FlutterFire CLI creates a new Firebase app in your Firebase project.
- You can select either to use an existing Firebase project or to create a new Firebase project. If you already have apps registered in an existing Firebase project, the FlutterFire CLI will attempt to match them based on your current Flutter project configuration.
- Creates a Firebase configuration file (firebase_options.dart) and adds it to your lib/ directory.
- (for Crashlytics or Performance Monitoring on Android) Adds the required product-specific Gradle plugins to your Flutter app.
Step 3: Initialise Firebase in your app
-
From your Flutter project directory, run the following command to install the core plugin:
your-flutter-proj$ flutter pub add firebase_core
-
From your Flutter project directory, run the following command to ensure that your Flutter app's Firebase configuration is up-to-date:
your-flutter-proj$ flutterfire configure
-
In your lib/main.dart file, import the Firebase core plugin and the configuration file you generated earlier:
import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart';
-
Also in your lib/main.dart file, initialise Firebase using the DefaultFirebaseOptions object exported by the configuration file:
await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );
-
Rebuild your Flutter application:
your-flutter-proj$ flutter pub add firebase_core
Configuring firebase for android
Important: It is possible to register multiple apps within the same Firebase project. However, please keep in mind that the Google Analytics service is linked to the Firebase project and not to a single app. This means that within the linked Google Analytics dashboard you, or anyone you grant access to your analytics dashboard, will be able to view analytical data for all apps registered in the same Firebase project.
Step 1: Open your Firebase project.
If you haven’t created a project yet then follow main step 2. Creating a Firebase project
Step 2:
Click on the Android logo below the text "Get started by adding Firebase to your app".
Step 3:
In Firebase, paste the Bundle ID in the Android package name input field and click Register app to continue.
Step 4:
Download the google-services.json file. You'll have to upload this file during the Android publishing process in AppMachine. Click Next to continue.
Step 5:
In Step 3 ‘Add Firebase SDK' click Next without making any changes.
Step 6:
In Step 4 'Next steps' click the Continue button to complete the Firebase Android app registration.
Configuring firebase for iOS
Step 1: Open your Firebase project.
If you haven’t created a project yet then follow main step 2. Creating a Firebase project
Step 2:
Click on the iOS logo below the text "Get started by adding Firebase to your app".
Step 3:
In Firebase, paste the Bundle ID in the Apple bundle ID input field and click Register app to continue.
Step 4:
Download the GoogleService-info.plist file and Click Next to continue.
Step 5:
In Step 3 ‘Add Firebase SDK' click Next without making any changes.
Step 6:
In Step 4 'Add initialization code' click Next without making any changes
Step 7:
In Step 5 'Next steps' click the Continue button to complete the Firebase iOS app registration.
Adding firebase services
Firebase Authentication
Firebase Authentication
will provide backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.-
Add Firebase Authentication to your app
Step 1: From the root of your Flutter project, run the following command to install the plugin
flutter pub add firebase_auth
Step 2: Once complete, rebuild your Flutter application
flutter run
Step 3: Import the plugin in your Dart code
import 'package:firebase_auth/firebase_auth.dart';
Step 4: Configure firebase initialization in dart code
Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); }
To check user’s auth state
FirebaseAuth.instance.authStateChanges() .listen((User? user) { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); } });
Firebase Realtime Database
The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronised in realtime to every connected client. When you build cross-platform apps with our Apple platforms, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.
Prerequisites
-
Install firebase_core and add the initialization code to your app if you haven't already.
-
Add your app to your Firebase project in the Firebase console.
Add Firebase Realtime Database to your app
Step 1: From the root of your Flutter project, run the following command to install the plugin
flutter pub add firebase_database
Step 2: Once complete, rebuild your Flutter application
flutter run
Step 3: Import the plugin in your Dart code
import 'package:firebase_database/firebase_database.dart';
To use the default Database instance, call the instance getter on FirebaseDatabase
FirebaseDatabase database = FirebaseDatabase.instance;
If you'd like to use it with a secondary Firebase App, use the static instanceFor method:
FirebaseApp secondaryApp = Firebase.app('SecondaryApp'); FirebaseDatabase database = FirebaseDatabase.instanceFor(app: secondaryApp);
If you'd like to use a different RTDB instance on the same project, you can pass in a databaseUrl using the static instanceFor method:
Firebase Cloud Messaging
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.
Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4000 bytes to a client app.
Add Firebase Cloud Messaging to your app
Step 1:
Install and initialize the Firebase plugins for Flutter if you haven't already done so.
Step 2:
From the root of your Flutter project, run the following command to install the plugin
flutter pub add firebase_messaging
Step 3:
Once complete, rebuild your Flutter application
flutter run
To get fcmToken
final fcmToken = await FirebaseMessaging.instance.getToken()
Cloud Storage for Firebase
Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage service built for Google scale. The Firebase SDKs for Cloud Storage add Google security to file uploads and downloads for your Firebase apps, regardless of network quality.
You can use our client SDKs to store images, audio, video, or other user-generated content. On the server, you can use the Firebase Admin SDK to manage buckets and create download URLs, and use Google Cloud Storage APIs to access your files.
Add the Cloud Storage SDK to your app
Step 1:
From the root of your Flutter project, run the following command to install the plugin
flutter pub add firebase_storage
Step 2:
Once complete, rebuild your Flutter application
flutter run
Step 3:
Import the plugin in your Dart code
import 'package:firebase_storage/firebase_storage.dart';
Upload Files
// Create a storage reference from our app
final storageRef = FirebaseStorage.instance.ref();
// Create a reference to "mountains.jpg"
final mountainsRef = storageRef.child("mountains.jpg");
final mountainImagesRef = storageRef.child("images/mountains.jpg");
// While the file names are the same, the references point to different files
assert(mountainsRef.name == mountainImagesRef.name);
assert(mountainsRef.fullPath != mountainImagesRef.fullPath);
Get a download URL
After uploading a file, you can get a URL to download the file by calling the getDownloadUrl() method on the Reference:
await mountainsRef.getDownloadURL();
Testing Firebase Integration
-
Integration Testing with Flutter
To test Flutter apps with Firebase Test Lab, you can write Flutter integration tests, build Android APKs or iOS test zip files, and run as regular Android instrumentation tests or iOS XCTests.
-
Flutter integration test types
Flutter supports three types of tests: unit tests, widget tests, and integration tests. A unit test verifies the behaviour of a method or class. A widget test verifies the behaviour of Flutter widgets without running the app itself. An integration test, also called end-to-end testing or GUI testing, runs the full app.
To learn more about integration tests, see Flutter integration testing.
-
Write Flutter integration tests
To learn how to write integration tests, see the project setup section of the Flutter integration tests documentation. Optionally, you can follow running using Flutter command to run and verify the tests locally.
-
Test on Test Lab
You can use Test Lab with both Android and iOS targets.
-
Android setup
Follow the instructions in the Android Device Testing section of the README.
-
iOS setup
Follow the instructions in the iOS Device Testing section of the README.
Conclusion
There you have it: a thorough guide that walks you through adding Firebase to your Flutter app. By integrating your Flutter application with Firebase, you unlock powerful features that can dramatically enhance your app's functionality and provide useful insights into its performance. Whether it be aiding user authentication, enabling synchronisation of data across devices and sessions through Cloud Firestore, or harnessing the power of Google Analytics to understand user behaviour, Firebase truly amplifies what you can achieve with your Flutter app. Remember, adding Firebase to a Flutter app is not the end but just the beginning of an exciting journey into creating powerful, scalable, and function-rich applications. So, why wait? Power your Flutter app with Firebase today!