livesdmo.com

Unlocking the Power of Firebase Cloud Functions in Flutter

Written on

Getting Started with Firebase Cloud Functions

In this guide, I will walk you through the process of writing, deploying, and invoking a cloud function using Firebase from your Flutter application.

Firebase Cloud Functions Overview

Harnessing External Processing Power

Firebase Cloud Functions is a Google service that allows you to run code in the cloud, offering significant advantages in scalability. With Firebase, your app can effectively handle a large number of users without performance issues. This article will cover several key topics:

๐Ÿ”น Configuring Firebase with your app

๐Ÿ”น Initializing cloud functions

๐Ÿ”น Crafting a cloud function

๐Ÿ”น Deploying a cloud function

๐Ÿ”น Invoking a cloud function

๐Ÿ”น Using functions as HTTP request endpoints

๐Ÿ”น Scheduling functions

๐Ÿ”น Selecting regions

๐Ÿ”น Logging

Want to dive deeper? Check out my ebook for extensive guides on building Flutter apps with Firebase, available on Gumroad!

Configuring Firebase and Your App

To get started, you need to set up Firebase and connect it to your application. For detailed instructions on this process, please refer to the linked article.

Next, install the Firebase Cloud Functions package by adding it to your pubspec.yaml file or via the command line. If you need more guidance, consult the installation manual or the previous article.

With the setup complete, you can begin writing your functions! ๐ŸŽ‰

Initializing Cloud Functions

Log in to Firebase by executing the command firebase login. Next, run firebase init functions from your project's root directory. The tool will prompt you with several questions that you'll need to answer, such as:

๐Ÿ”น Are you ready to continue? โ†’ Yes

๐Ÿ”น Please select an option: โ†’ Use an existing project

๐Ÿ”น What language do you want to use for Cloud Functions? โ†’ JavaScript

๐Ÿ”น Would you like to use ESLint to catch potential errors and enforce style? โ†’ No

๐Ÿ”น Do you want to install dependencies with npm now? โ†’ Yes

After completing these steps, a new functions folder will appear in your project structure.

Writing a Cloud Function

Now, let's write some code that will run in the cloud. For our example, we will create a function that takes a string as input and converts it to uppercase. This simple code will illustrate what you can achieve.

Open index.js in the functions folder and include the following code:

exports.toUpperCase = functions.https.onCall((data, context) => {

return data.text.toUpperCase();

});

Here, we define a callable method called toUpperCase with two parameters. The data parameter contains the string we want to modify, and the second parameter is a CallableContext, which is not utilized in this example. We simply use JavaScript's built-in toUpperCase method and return the result. It's that straightforward! ๐ŸŽ†

๐Ÿ’ก Ensure your code is idempotent! This means it should produce the same output even when called multiple times, which simplifies the process of retrying failed executions.

๐Ÿ’ก You can opt for TypeScript as your programming language. Just select "TypeScript" during the initialization prompt instead of "JavaScript." Currently, these are the only supported languages.

Deploying a Cloud Function

Deployment is a breeze! Simply run the command firebase deploy --only functions and wait for the process to complete. It may take up to five minutes for your dashboard to refresh and display the updated information about logs and function usage.

Calling a Cloud Function

A callable function can be invoked using the method functions.https.onCall((data, context) => {...});. The Firebase dashboard does not differentiate between callable functions and HTTP endpoints; both triggers are categorized as "Request."

To call a function named toUpperCase(), refer to the following code example:

const result = await firebase.functions().httpsCallable('toUpperCase')({ text: "hello" });

Defining an HTTP Request Endpoint

Using the syntax functions.https.onRequest((request, response) => {...});, you can create an HTTP endpoint that can be called by other web services. This allows you to define interfaces for third-party applications to interact with your data or logic. You do not necessarily need the Firebase package to call endpoints, but you will require something to create requests, such as the http or Dio packages. Hereโ€™s an example:

๐Ÿ’ก Remember to replace the link to the function with your deployed version!

For those unfamiliar with sending HTTP requests in Flutter, I have an article with demo code that could be beneficial.

โ— By default, an HTTP endpoint is accessible to anyone. Be sure to implement security measures like authorization tokens. For an official example of securing your endpoints, click here.

Scheduling a Function

You can also set a function to run on a schedule. The interval can be specified using the App Engine cron.yaml syntax or the traditional Unix crontab syntax. Hereโ€™s an example that executes a function every 10 minutes:

exports.scheduledFunction = functions.pubsub.schedule('every 10 minutes').onRun((context) => {

console.log('This will be run every 10 minutes!');

});

For a list of supported timezones, click here.

Selecting Regions

Firebase offers different regions that impact both pricing and latency. You can specify your preferred region using the region() method with a valid region name as an argument. For instance: functions.region("europe-west3"). I recommend choosing the nearest region to your location and you can also specify multiple regions separated by commas.

Logging

To monitor function executions, you can utilize logging. The output will be visible in your Firebase Functions dashboard.

const functions = require("firebase-functions");

functions.logger.log("This is a log:", someObj);

functions.logger.info("This is an info message:", someObj);

functions.logger.warn("This is a warning:", someObj);

functions.logger.error("This is an error message:", someObj);

For additional details on logging, refer to the official documentation.

Callable Functions vs. HTTP Functions

Callable functions and HTTP functions are quite similar. A callable function is essentially an HTTP function with special request parameters. The main distinction lies in that authentication tokens for Firebase and Firebase Cloud Messaging, along with App Check tokens, are automatically included in the request for callable functions if available. Additionally, callable functions validate these tokens by default, meaning you gain authentication features without extra work.

On the other hand, HTTP functions do not come with built-in access control, so you will need to implement security measures on your own. However, you can still invoke a callable function via an HTTP request by supplying the correct data.

โœ” Use callable functions if your app is the sole consumer.

โœ” Opt for HTTP functions if you have third-party consumers (like a public REST API) but ensure you implement access control and other security measures.

Conclusion

Firebase Cloud Functions present an efficient way to leverage external processing power in your Flutter application. Hereโ€™s a brief demo video showcasing the source code.

You can find the complete example source code on my GitHub page.

This article is part of the Flutter Firebase Compendium, which contains numerous tutorials and guides on how to maximize Firebase's capabilities in Flutter applications.

Enhance your Firebase knowledge for Flutter developers with my ebooks!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Understanding the Long-Term Impacts of Alcohol on Reward Systems

Exploring how alcohol creates instant gratification and the long-term consequences on mental health and personal growth.

Unlocking the Wisdom of Carl Jung: Your Path to Self-Discovery

Discover how Carl Jung's insights can help you uncover your true self and navigate life's complexities.

The Forgotten Artillery: World War I's Stratospheric Shells

Explore the remarkable story of the first man-made object in the stratosphere, a shell fired during World War I, and its implications.

The Cosmic Discovery: How a Hiss Unveiled the Universe's Secrets

Discover how the accidental finding of the cosmic microwave background transformed our understanding of the universe.

Discovering Your True Purpose: Insights from a Leading Podcaster

Explore how to uncover your lifeโ€™s purpose through insights from renowned podcaster Jay Shetty.

The Influence of H.G. Wells on Atomic Warfare Predictions

Explore how H.G. Wells's novel predicted and possibly influenced the creation of the atomic bomb.

The Power of Caring Less: Finding Meaning Amidst Excess

Discover how to prioritize what truly matters in life by caring less and focusing on meaningful experiences.

Empowering Women Over 30: Strategies for Enhanced Mental Health

Discover effective strategies for women over 30 to boost mental health through diet and exercise.