1 of 67

Improving Firebase Backend�for Flutter App through �Cloud Functions

Sasha Denisov, EPAM

Flutter and Dart GDE

2 of 67

About me

2

CHIEF SOFTWARE ENGINEER II

SASHA DENISOV

Sasha is an experienced software developer with a rich background, in IT for more than 20 years. He worked with different stacks in backend, frontend and mobile fields, but since 2018 his main interest is Flutter. Sasha is Chief Software Engineer and Head of Flutter Discipline in EPAM. In addition, he is a Flutter and Dart Google Developer Expert and Co-Organizer of Flutter Berlin Meetup community

3 of 67

Cloud Functions for Firebase

4 of 67

Clouds

5 of 67

Cloud Service Characteristics

  • On-demand self-service
  • Broad network access
  • Resource pooling
  • Rapid elasticity
  • Measured service

6 of 67

Evolution of Cloud Services

7 of 67

Function

Application

Runtime

Container

OS

Virtualization

Hardware

IaaS

Function

Application

Runtime

Container

OS

Virtualization

Hardware

CaaS

Function

Application

Runtime

Container

OS

Virtualization

Hardware

PaaS

Function

Application

Runtime

Container

OS

Virtualization

Hardware

FaaS

User Management

User Management (scalable unit)

Service Provider Management

8 of 67

Cloud Functions

9 of 67

The question is

9

 

What exactly Firebase backend is?

10 of 67

Firebase

10

11 of 67

Traditional server backend

11

12 of 67

Firebase serverless backend

12

13 of 67

Flutter Application: Movies

13

 

https://github.com/denisovav/flutter_tv

14 of 67

Let’s add few Firebase Services

14

 

Firestore database for storing movies data

Storage for storing images and videos

Authentication for access control

15 of 67

Adding Firebase backend

https://github.com/DenisovAV/flutter_tv/tree/firebase_support

16 of 67

Authentication Added

16

 

https://pub.dev/packages/firebase_ui_auth

17 of 67

Cloud Function Trigger

How to to trigger a function?

18 of 67

Authentication Triggers

  1. onCreate
  2. onDelete

19 of 67

Authentication Functions Using Scenarios

  1. Send welcome emails to new users
  2. Create a new document in a Firestore collection when a user is created
  3. Send a notification to other users when a user is created
  4. Delete all user date when a user is deleted

20 of 67

Scenario

New User

21 of 67

How to create a Cloud Function?

  1. Go to your project folder
  2. Set up Node.js and the Firebase CLI
  3. Connect to the project using Firebase CLI

npm -g install firebase-tools

firebase login

firebase init functions

4. Write your function code using JS or TS (functions/index.js)

5. Deploy functions to a production environment

firebase deploy --only functions

22 of 67

Supported Languages

23 of 67

AI ?

24 of 67

25 of 67

26 of 67

import * as functions from "firebase-functions";

export const createUser =

exports.createUser = functions.region("europe-west1").auth.user().onCreate(async (user) => {

if (user.photoURL) {

const avatarFileName = `avatars/${user.uid}.jpg`;

const response = await axios.get(user.photoURL, {responseType: "arraybuffer"});

const buffer = Buffer.from(response.data, "binary");

const file = bucket.file(avatarFileName);

await file.save(buffer, {contentType: "image/jpeg", public: true});

const uuid = randomUUID();

updatedAvatarURL = `https://firebasestorage.googleapis.com/v0/b/${bucket.name}` +

`/o/${encodeURIComponent(file.name)}?alt=media&token=${uuid}`;

}

// Create a new document in the `users` collection.

const doc = admin.firestore().collection("users").doc(user.uid);

doc.set({

user.email, displayName: user.displayName, avatarURL: updatedAvatarURL, admin: false});

});

27 of 67

28 of 67

29 of 67

30 of 67

31 of 67

Administrator Capabilities

31

 

32 of 67

Storage Triggers

  1. onFinalize
  2. onDelete
  3. onArchive
  4. onMetadataUpdate

  1. onObjectFinalized
  2. onObjectDeleted
  3. onObjectArchived
  4. onMetadataUpdated

33 of 67

Cloud Functions Generation 2

33

 

34 of 67

Supported Languages in Gen2

35 of 67

Cloud Run

35

 

36 of 67

Dart on Server Side

36

 

Serverpod

Dart Frog

37 of 67

Cloud Run

37

 

38 of 67

Storage Functions Using Scenarios

  1. Image Processing
  2. Notifications
  3. Data validation and Sanitization
  4. File Metadata Management
  5. Backup and Archiving
  6. Access Control
  7. Audio and Video Processing
  8. Integration with Third-party Services
  9. Analytics
  10. Cleanup Operations

39 of 67

Scenario

Image Uploaded

40 of 67

import * as functions from "firebase-functions/v2";

export const compressImage =

exports.compressMedia = functions.storage.onObjectFinalized({cpu: 2}, async (event) => {

const fileBucket = event.data.bucket; // Storage bucket containing the file.

if (!contentType.startsWith("image/")) {

return console.error("This is not an uploaded image.");

}

const bucket = admin.storage().bucket(fileBucket);

const downloadResponse = await bucket.file(filePath).download();

const imageBuffer = downloadResponse[0];

const meta = await sharp(imageBuffer).metadata();

const rotatedBuffer = (meta.width! < meta.height! ? await sharp(imageBuffer).rotate(90).toBuffer() : imageBuffer);

const processedBuffer = await sharp(rotatedBuffer).resize({width: 600, height: 300, withoutEnlargement: true,

}).toBuffer();

// Upload the processed image.

const metadata = {contentType: contentType};

const file = bucket.file(filePath);

await file.save(processedBuffer, {

metadata: metadata,

});

return console.log("Image uploaded!");

});

41 of 67

42 of 67

The question is

42

 

How to notify users about new content?

43 of 67

  1. onDocumentCreated
  2. onDocumentUpdated
  3. onDocumentDeleted
  4. onDocumentWritten

Firestore Triggers

  1. onCreate
  2. onUpdate
  3. onDelete
  4. onWrite

44 of 67

Firestore Functions Using Scenarios

  1. Data validation and Sanitization
  2. Notifications
  3. Data Aggregation
  4. Integration with External Services
  5. Automatic Data Management
  6. Access Control
  7. Chaining Database Operations
  8. Complex Business Logic
  9. Analytics
  10. SEO Operations

45 of 67

Scenario

Document Added

46 of 67

import * as functions from "firebase-functions/v2";

functions.setGlobalOptions({

region: "europe-west1",

});

export const sendPushNotification = functions.firestore.onDocumentCreated("movies/{id}", async (event) => {

const movie = event.data;

const name = movie.get("name");

const image = movie.get("image");

const notification: admin.messaging.Message = {notification: {title: `${name} added!`,

body: "New movie was added to movies catalog, please enjoy!", imageUrl: image, },

topic: "movies",

};

try {

const response = await admin.messaging().send(notification);

console.log("Successfully sent message:", response);

} catch (error) {

console.error("Error sending message:", error);

}

});

47 of 67

48 of 67

Firebase Cloud Messaging

48

 

49 of 67

Rest API

49

 

50 of 67

export const getMoviesData = functions.https.onRequest(async (req, res) => {

const snapshot = await admin.firestore().collection("movies").get();

if (snapshot.empty) {

res.status(400).send({error: "Collection of movies is empty."});

return;

}

const data: any[] = [];

snapshot.forEach((doc) => {

data.push({

id: doc.id,

...doc.data(),

});

});

res.status(200).send({data: data});

});

51 of 67

52 of 67

52

 

53 of 67

Callable

53

 

await FirebaseFunctions.instance.httpsCallable('yourFunctionName').call();

54 of 67

More Triggers

  1. Firebase Alerts Triggers
  2. Blocking Auth Triggers
  3. Analytics Triggers
  4. Remote Config Triggers
  5. Test Lab Triggers
  6. Pub/Sub Triggers

55 of 67

Custom Events

55

 

56 of 67

Google Cloud Platform

56

 

57 of 67

Google Cloud Platform

57

 

58 of 67

Google Cloud Platform

58

 

59 of 67

60 of 67

Java Example

60

 

61 of 67

Supported Languages

61

 

  • Node.js (12, 14, 16, 18, and 20)
  • Python (3.7, 3.8, 3.9, 3.10 and 3.11)
  • Go (1.13, 1.16, 1.18, 1.19, 1.20 and 1.21)
  • Java (11 and 17)
  • .NET (6.0 and Core 3.1)
  • Ruby (2.6, 2.7, 3.0 and 3.2)
  • PHP (7.4, 8.1 and 8.2)

62 of 67

63 of 67

64 of 67

Cloud Run

64

 

65 of 67

66 of 67

The future is bright (especially for Flutter developers)

66

 

67 of 67

THE FINAL SLIDE

https://github.com/DenisovAV/flutter_tv/tree/firebase_support

@shuregdenisov

THANK YOU!�QUESTIONS?