Flutter Tutorial: Firebase (Cloud Firestore)

Today, we are going to see how to connect to Firebase (Cloud Firestore) using flutter. Before we start, let's take take a look in some question below

What is Firebase ?
Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014

What is Cloud Firestore?
is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps - at global scale.

What we what to create from this technology?
We want to create a simple application called movie votes. From this very basic application, we will see how to configure Firebase which will ready for our project and how to perform get/insert/update/delete operation into Firebase (Cloud Firestore) using flutter.

So, let's start...

1. Create new project

Start to create a project name tutorial_firebase by run below command in command promt:

flutter create tutorial_firebase
view raw create.bat hosted with ❤ by GitHub
2. Clean up your basic code

Once all set, open project using your favorite IDE (for my case, i was using Visual Studio Code). Then, just clean up the very basic sample code, and run it..

3. Configure your Firebase

Open your Firebase Console.
Click add project and it will show you a form to ask you to put your project name



Just put any name you like and click Create Project. Wait for the process.
Once it done click Continue and it will redirect you to Project Overview page



Click on Android Icon to start create for android project and it will show you below page



The package name, you can find in below folder in your project



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorial_firebase">
Put your project name, in my case is com.example.tutorial_firebase and then put any name of project you like. click Register App



In this page, you need to download google-services.json and put in below path



Click Next



This page, guide you how yo setup firebase to your application. Please find full setup as below (we skip setup for implementation 'com.google.firebase:firebase-core:17.0.0' because it use for analytics)

Note: This setting is migrate using androidX because flutter library for cloud_firestore required androidX plugins 

Create below file

android/app/gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Modify below file

android/build.gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0' // Google Services plugin
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
view raw build.gradle hosted with ❤ by GitHub
android/app/build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.tutorial_firebase"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
apply plugin: 'com.google.gms.google-services'
view raw build.gradle hosted with ❤ by GitHub
After everything is set, you can click Next and skip for the connection testing. Now the page will redirect to overview. and click database menu at left to open firebase database setup



Click Create Database, and follow the instruction. Then it will redirect to database page

Add your first collection and add some data (for my case I was add collection name movie_to_vote)

Note: keep your collection name because it will use for getting the connection

4. Connect to Firebase

Add flutter plugin in below file
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
cloud_firestore: ^0.12.5+2
view raw pubspec.yaml hosted with ❤ by GitHub

Import plugin in your code and create a connection to your collection

lib/main.dart
.....
import 'package:cloud_firestore/cloud_firestore.dart';
.....
class _MyHomePageState extends State<MyHomePage> {
final CollectionReference _movieCollection = Firestore.instance.collection("movie_to_vote");
.....
view raw main.dart hosted with ❤ by GitHub

5. Get operation 

Use StreamBuilder to display the collections.

lib/main.dart
....
body: StreamBuilder(
stream: _movieCollection.snapshots(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
return _mainContent(snapshot.data.documents[index]);
},
);
}
},
),
....
view raw main.dart hosted with ❤ by GitHub

6. Update operation 

lib/main.dart
....
onTap: () {
data.reference.updateData({"votes": data["votes"] + 1});
},
....
view raw main.dart hosted with ❤ by GitHub

7. Insert operation 

lib/main.dart
....
FlatButton(
child: Text("Save"),
onPressed: () {
_movieCollection.document().setData({
"name": _textMovieController.text,
"votes": 0
}).whenComplete(() => Navigator.of(context).pop());
},
....
view raw main.dart hosted with ❤ by GitHub

8. Update operation

lib/main.dart
....
FlatButton(
child: Text("Delete"),
onPressed: () {
dataPress.reference.delete();
Navigator.of(context).pop();
},
)
....
view raw main.dart hosted with ❤ by GitHub


Full Video


Source Code

Flutter Tutorial: Firebase (Cloud Firestore)

Comments

Popular posts from this blog