Flutter with Firebase

What is Firebase?

DSC BVP Pune
7 min readMar 14, 2021

Firebase can not only be used as a dummy backend API but it is a fully managed backend service that provides the services which include real-time database, file storage, authentication, push notifications, analytics, on-demand server side code (cloud functions), etc.

To build our App we can use:

Firebase ML Kit: Using machine learning capabilities was only possible over the cloud as it required a lot of compute power, high-end hardware, etc. But mobile devices nowadays have become much more powerful and our Algorithms more efficient. All this has led to on-device machine learning as a possibility.

Firebase ML Kit provides users the features of Machine Learning such as Face Recognizance, Language Translator, etc. In short ML kit provides the mobile SDK(Software Development Kit) that can be easily integrated with Android as well as IoS Apps. ML Kit brings Google’s machine learning expertise to Android and iOS apps in a powerful yet easy-to-use package.

For more: https://firebase.google.com/docs/ml

Cloud Functions: Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your JavaScript or TypeScript code is stored in Google’s cloud and runs in a managed environment. There’s no need to manage and scale your own servers.

For More: https://firebase.google.com/docs/functions

Cloud Firestore: Cloud Firestore is a massively scalable, cloud-hosted, NoSQL, real-time database. Cloud Firestore has SDKs for mobile apps and server components, but the underlying database product is the same. If you’re a Google Cloud developer using Firestore as part of your backend architecture, or you’re a Firebase developer whose users access it directly from your client app, Cloud Firestore stores data and scales in exactly the same way.

For More: https://firebase.google.com/docs/firestore

Hosting: Firebase Hosting allows fast and secure hosting for our web application, static and dynamic content, and microservices. It is production-grade web content hosting for the developers. We can easily and quickly deploy web apps and serve both static and dynamic content to a global content delivery network with only a single command. We can pair Firebase Hosting with Cloud Function or Cloud Run for building and hosting microservices on Firebase.

For More: https://firebase.google.com/docs/hosting

Real-time Database: The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

For More: https://firebase.google.com/docs/database

Cloud Storage: A developer might want to enable users to store images and videos captured on their devices, then let the users view the files on other devices or share them with friends. Firebase provides SDKs (Android, iOS, web, Unity, C++) for uploading and downloading objects in storage, directly from the app, bypassing the need for any other backend components.

For More: https://firebase.google.com/docs/storage

Authentication: Firebase Authentication provides 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.

For More: https://firebase.google.com/docs/auth

To learn Firebase Authentication in Flutter : https://medium.com/firebase-tips-tricks/how-to-use-firebase-authentication-in-flutter-50e8b81cb29f

Flutter is Google’s SDK for building Mobile Apps and Firebase gives us the access to backend services for the Mobile Applications.

We will form a ChatApp to learn about the Firebase Integration. This is the basic structure.

Building a ChatApp from Scratch

Using the Firebase Flutter Packages for Auth and Database

Working with Real time data

Image Upload

-> Build a New App

Add the dependencies in pubspec.yaml file

cloud_firestore | Flutter Package

Go to Firebase Console and add a new project

https://console.firebase.google.com/u/0/

Step 1 : In the Firebase Console, click Add project.

Step 2 : Enter a name for your Firebase project and click “Continue”.

Step 3 : Next, configure Google Analytics. If you don’t want to use Analytics, so you can turn it off, then click “Create project”.

Step 4 : After a minute or so, your Firebase project will be ready. Click Continue.

Step 5 : After you’ve created a Firebase project, you can configure one (or more) apps to use that Firebase project. All you need to do is:

  • Register your app’s platform-specific ID with Firebase
  • Generate configuration files for your app, then add them to your project folders

Step 6 : In the Firebase Console, select Project Overview in the left nav, then click the Android button under “Get started by adding Firebase to your app”.

Step 7 : For Android and ios respectively refer to :

https://codelabs.developers.google.com/codelabs/flutter-firebase/#6

Step 8 : Firebase Project is Ready.

Authentication

For Authentication read out the following article:

https://medium.com/firebase-tips-tricks/how-to-use-firebase-authentication-in-flutter-50e8b81cb29f

Database

In cloud firestore Click on Create Database.

In order to structure your data, you define collections which contain documents.Each document contains fields that contain the actual data. You can reference an individual document using its unique path, or you can query a collection for documents whose fields contain the data you’re looking for.

Chats -> Id -> Messages -> Id -> Text

Import cloud_firestore in your dart filename chatscreen.dart

Attach the file in your project given in this link.

https://drive.google.com/file/d/18jWlyeCO6PdpxBw9y6wHfzvm_iYtuLqN/view?usp=sharing

Here Firestore will give a new instance which is an active instance managed on our behalf and it gives us access to the methods like “collection” and here set the path and then will call a snapshot which gives us the stream and it allows us to add a listener which will listen as the data changes.

Now Run.

You will see that it will give instance of Query Snapshot

And when you will print(data.documents) it will give the instance of QuerySnapshot Documents

Now print

Data.documents[0][‘text’]

It will access the document at 0th index and the text message which we have added.in the document in firestore.

It will print “Hello”

-> StreamBuilder will listen to the data when it changes as the value is changing continuously due to the new messages.

Bind up the whole thing with StreamBuilder . Stream will give the snapshot of the latest data.

To learn more about StreamBuilder

https://api.flutter.dev/flutter/widgets/StreamBuilder/StreamBuilder.html

For the New Message

Declared an empty message _enteredString.

In function _sendMessage we have defined an user which will take the currentUser and userData which was defined to access the user data.

Add method is used to add the data into the cloud firestore database in the form of a map.

Then when we will call the sendMessage then it will add the new message in the firebase which was entered by the user.

Here we have also added createdDate , userId and userName.

Uid we will get when the user will login into the app.

To learn about all the methods of Cloud Firestore:

https://firebase.flutter.dev/docs/firestore/usage/

Difference between StreamBuilder and FutureBuilder

FutureBuilder is used for one time response, like taking an image from Camera, getting data once from native platform (like fetching device battery), getting file reference, making an http request etc.

On the other hand, StreamBuilder is used for fetching some data more than once, like listening for location updates, playing music, stopwatch, etc.

Example between them :

https://stackoverflow.com/a/56378676

Here we have bound up the streambuilder with a futurebuilder. When the connection state is waiting then it will show the indicator and once the future is called data will be fetched from the firestore and will be shown on the screen.

https://medium.com/flutter-community/a-guide-to-using-futures-in-flutter-for-beginners-ebeddfbfb967

Image Upload

-> Adding an Image Picker

Add the dependency in pubspec.yaml file

https://pub.dev/packages/image_picker

pickedImageFile is the imageFile which is picked by the user and it will of type future as pickImage returns Future.

pickedImage: We are storing the pickedImageFile into the pickedImage so that preview of the image can be shown in the app.

-> Image Upload and Validating Image

Add dependency firebase_Storage

https://pub.dev/packages/firebase_storage

ref() gives us the access of the cloud storage bucket

child(path) allows us to store the path where we have to store the image file.

Chained another child which will consist of the name of the image.

ref.putFile() as the name said it will put the file into the given path.

onComplete allows us to return the future.

To get the Image URL

ref.getDownloadURL() will give the imageURL which is stored in the bucket.

Displaying the Image

We have added the downloaded imageURL into the firestore so that it will be easy to access and get the image hence now that image can be easily shown into the chat message.

This is how you will be able to get and display the image from Firebase.

Final Result:

For Complete ChatApp visit Github Repo : https://github.com/aayushigupt/firebase_chatapp

Conclusion

So, that’s it for this article. Thanks for reading.

Written By
Aayushi Gupta

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

DSC BVP Pune
DSC BVP Pune

No responses yet

Write a response