Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Firebase Integration

Firebase Integration

Firebase is a mobile and web application development platform provided by Google. This section will introduce how to integrate Firebase in Flutter.


Firebase Overview

Firebase provides a variety of backend services, including authentication, database, storage, analytics, and more.

Service Description
Firebase Auth User Authentication
Cloud Firestore Cloud NoSQL Database
Realtime Database Realtime Database
Cloud Storage Cloud File Storage
Firebase Analytics App Analytics
Cloud Functions Cloud Serverless Functions

Installation and Configuration

Add Dependency



dependencies:

  firebase_core: ^2.0.0

  firebase_auth: ^4.0.0

  cloud_firestore: ^4.0.0

Firebase Initialization

Example: Initializing Firebase

import

'package:firebase_core/firebase_core.dart'

;

import

'package:flutter/material.dart'

;

void

main

(

)

async

{

  WidgetsFlutterBinding.

ensureInitialized

(

)

;

 

// Initialize Firebase

  await Firebase.

initializeApp

(

)

;

  runApp

(

const

MyApp

(

)

)

;

}


Firebase Auth - User Authentication

Example: Email and Password Login

import

'package:firebase_auth/firebase_auth.dart'

;

class

AuthService

{

 

final

FirebaseAuth _auth

=

FirebaseAuth.

instance

;

 

// Register

  Future

<

User

?

registerWithEmail

(

String email

,

String password

)

async

{

   

try

{

     

final

credential

=

await _auth.

createUserWithEmailAndPassword

(

        email

:

email

,

        password

:

password

,

     

)

;

     

return

credential.

user

;

   

}

on FirebaseAuthException

catch

(

e

)

{

      print

(

'Registration failed: ${e.message}'

)

;

     

return

null

;

   

}

 

}

 

// Login

  Future

<

User

?

signInWithEmail

(

String email

,

String password

)

async

{

   

try

{

     

final

credential

=

await _auth.

signInWithEmailAndPassword

(

        email

:

email

,

        password

:

password

,

     

)

;

     

return

credential.

user

;

   

}

on FirebaseAuthException

catch

(

e

)

{

      print

(

'Login failed: ${e.message}'

)

;

     

return

null

;

   

}

 

}

 

// Log out

  Future

<

void

signOut

(

)

async

{

    await _auth.

signOut

(

)

;

 

}

 

// Listen for login status

  Stream

<

User

?

get

authStateChanges

{

return

_auth.

authStateChanges

(

)

;

 

}

}


Cloud Firestore - Database

Example: Basic Firestore Operations

import

'package:cloud_firestore/cloud_firestore.dart'

;

class

FirestoreService

{

 

final

FirebaseFirestore _db

=

FirebaseFirestore.

instance

;

 

// Add document

  Future

<

void

addUser

(

Map

<

String

,

dynamic

user

)

async

{

    await _db.

collection

(

'users'

)

.

add

(

user

)

;

   

// Or specify an ID

   

// await _db.collection('users').doc('user_id').set(user);

 

}

 

// Get a single document

  Future

<

Map

<

String

,

dynamic

?

getUser

(

String id

)

async

{

   

final

doc

=

await _db.

collection

(

'users'

)

.

doc

(

id

)

.

get

(

)

;

   

return

doc.

data

(

)

;

 

}

 

// Get all documents in a collection

  Future

<

List

<

Map

<

String

,

dynamic

getUsers

(

)

async

{

final

snapshot

=

await _db.

collection

(

'users'

)

.

get

(

)

;

   

return

snapshot.

docs

.

map

(

(

doc

)

=>

doc.

data

(

)

)

.

toList

(

)

;

 

}

 

// Conditional query

  Future

<

List

<

Map

<

String

,

dynamic

getUsersByAge

(

int

age

)

async

{

final

snapshot

=

await _db

        .

collection

(

'users'

)

        .

where

(

'age'

,

isGreaterThanOrEqualTo

:

age

)

        .

get

(

)

;

   

return

snapshot.

docs

.

map

(

(

doc

)

=>

doc.

data

(

)

)

.

toList

(

)

;

 

}

 

// Update document

  Future

<

void

updateUser

(

String id

,

Map

<

String

,

dynamic

data

)

async

{

    await _db.

collection

(

'users'

)

.

doc

(

id

)

.

update

(

data

)

;

 

}

 

// Delete document

  Future

<

void

deleteUser

(

String id

)

async

{

    await _db.

collection

(

'users'

)

.

doc

(

id

)

.

delete

(

)

;

 

}

 

// Realtime listening

  Stream

<

QuerySnapshot

watchUsers

(

)

{

return

_db.

collection

(

'users'

)

.

snapshots

(

)

;

 

}

}


Firebase Storage - File Storage

Example: File Upload

import

'package:firebase_storage/firebase_storage.dart'

;

import

'dart:io'

;

class

StorageService

{

 

final

FirebaseStorage _storage

=

FirebaseStorage.

instance

;

 

// Upload a file

  Future

<

String

?

uploadFile

(

File file

,

String path

)

async

{

   

try

{

     

final

ref

=

_storage.

ref

(

)

.

child

(

path

)

;

     

final

result

=

await ref.

putFile

(

file

)

;

     

return

await result.

ref

.

getDownloadURL

(

)

;

   

}

on FirebaseException

catch

(

e

)

{

      print

(

'Upload failed: ${e.message}'

)

;

     

return

null

;

   

}

 

}

 

// Download file URL

  Future

<

String

?

getDownloadURL

(

String path

)

async

{

   

try

{

     

final

ref

=

_storage.

ref

(

)

.

child

(

path

)

;

     

return

await ref.

getDownloadURL

(

)

;

   

}

on FirebaseException

catch

(

e

)

{

      print

(

'Failed to get URL: ${e.message}'

)

;

     

return

null

;

   

}

 

}

 

// Delete a file

  Future

<

void

deleteFile

(

String path

)

async

{

    await _storage.

ref

(

)

.

child

(

path

)

.

delete

(

)

;

 

}

}

Firebase provides powerful backend services and is the best choice for quickly building a backend for Flutter apps.