Flutter Firebase Integration and Accessing the Data from Cloud Firestore
Flutter and Firebase were updated recently which had many changes you need to do when you want to integrate Firebase with Flutter. In this article, I am showing you all the needed steps to be followed.
Step 1: Create a Firebase Project
First thing first, you have to create a new Firebase project. Please go to the firebase console and add a project with the name you want and then enable the google analytic for your project. You have to select the data center location and then press continue and you are all Set!
Step 2: Adding Flutter Application to Firebase.
As you know that now Flutter supports many platforms like IOS, Android, web if you want to create an app that runs on all platforms then you have to integrate that separately. In this article, I will explain How to integrate Android.
Step3: Adding package name:
To get the package name, you have to go to the AndroidManifest.xml file
Step 4: Download config file:
Add google-services. json file into your flutter project. This is a very important step. Please make sure you are putting this file in the right location. It should be added in-app folder. See Below:
First add dependencies in Project level build.gradle file
classpath 'com.google.gms:google-services:4.3.8'
Now You have to add dependencies in app level build.gradle file
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:28.2.1')
implementation 'com.google.firebase:firebase-analytics'
}
Again you have to add some more lines in the app level build.gradle file
- Change minSdkVersion 21 from 16
- Add multiDexEnabled true
minSdkVersion 21
multiDexEnabled true
multiDex allows your applications to have more third-party libraries.
Step5: Creating Firestore database.
Please click on Firestore data base which will prompt you to select the mode. Please select Test mode. See Below:
Step6: Creating Collection.
Click on the start collection and give name
Now you have to create document with insert Document ID with Auto-ID and add fields with data type and values.
If you want to add more data then you can add more documents.
This is the final look of Firestore database.
Now it’s time to start to writing code to access this data in flutter App
Step7 : Add dependencies in flutter file:
Add cloud_firestore an firebase_core dependencies in pubspec.yaml file and then click on pub get in Android studio.
cloud_firestore:
firebase_core :
( All Firebase products now depend on firebase_core
version (0.5.0+), therefore you need to add it in the pubspec.yaml
file: )
Step5 : Initailse the firebase
All Firebase versions have been updated and now you have to call Firebase.initializeApp()
before using any Firebase product you can call this in your main app or you can add in futureBuilder as well.
void main()async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
This is very important step otherwise you will get error saying
Step8 : Create Collection Reference object to work with database.
final ref = FirebaseFirestore.instance.collection("City");
Step9 : Read data from Database
1 . One-time Read
To read a collection or document once, you call DocumentReference.get
methods in FutureBuilder.
2 . Realtime changes
FlutterFire provides support for dealing with realtime changes to collections and documents. A new event is provided on the initial request, and any subsequent changes to collection/document whenever a change occurs (modification, deleted or added). for this you should use StreamBuilder
Both the CollectionReference
& DocumentReference
provide a snapshots()
method which returns a Stream
:
StreamBuilder(
stream: ref.snapshots(),
builder: (context,AsyncSnapshot<QuerySnapshot>snapshot){
if(snapshot.hasData){
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context,index){
return
Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Column(
children: [
Image.network(snapshot.data.docs[index]['image']),
Text(snapshot.data.docs[index]['name'],style: TextStyle(fontSize: 30,fontWeight: FontWeight.bold),),
SizedBox(height: 20,),
Text(snapshot.data.docs[index]['desc']),
],
),
),
),
);
});
}
else{
return CircularProgressIndicator();
}
}),
StreamBuilder:StreamBuilder requires 2 parameters,
stream: A method that returns a stream object
builder: widgets that will be returned during different states of a streambuilder.
QuerySnapshot
builder: (context,AsyncSnapshot<QuerySnapshot>snapshot)
A QuerySnapshot is returned from a collection query, and allows you to inspect the collection, such as how many documents exist within it, gives access to the documents within the collection, see any changes since the last query and more.
if(snapshot.hasData)
In Some cases, it might take little bit time to load the data and you can get error saying that data is null. To avoid this error, It is good practice to check first whether snapshot has any data .if snapshot has data then only return widget or return CircularProgrssIndicator().
if(snapshot.hasData){
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context,index){
return
Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Column(
children: [
Image.network(snapshot.data.docs[index]['image']),
Text(snapshot.data.docs[index]['name'],style: TextStyle(fontSize: 30,fontWeight: FontWeight.bold),),
SizedBox(height: 20,),
Text(snapshot.data.docs[index]['desc']),
],
),
),
),
);
});
}
In above code, we are returning Listview.Builder where itemCount: snapshot.data.docs.length,is length of the document list we have created in firebase.
You can find the Github link of the above program here! If you like this article, then do not forget to give your likes & claps! :-)
Thank you!