How To Work With Firebase Cloud Functions In Flutter Apps

Firebase category image

In this article, I will demonstrate how to work with Firebase Cloud Functions in Flutter apps in the most simple way.

Firebase Cloud Functions is a service from Google that enables you to execute code in the cloud. A major benefit is scalability. If your app has many users, you wonโ€™t have a bottleneck when using Firebase. I will show you how to work with Firebase Cloud Functions in Flutter apps in the most simple way. The following sub-topics will be covered in this article:

  • Setting up Firebase and your app
  • Initializing cloud functions
  • Writing a cloud function
  • Deploying a cloud function
  • Calling a cloud function
  • Functions as HTTP request endpoints
  • Scheduled functions
  • Regions
  • Logging

An In-Depth Firebase Guide For Flutter Developers!

This compendium is a comprehensive guide with many step-by-step guides and code examples. Learn the essentials of Firebase and enhance your apps with cloud services in no time!


Setting up Firebase and your app

At first, you need to set up Firebase and connect it with your app. Have a look at the following article for details about that.

The next step is to install the Firebase Cloud Functions package. Add it to your pubspec.yaml or use the command line. If you need further instructions, read the installation manual or the following article.

The setup is completed. You can now start writing your functions.

Initializing cloud functions

Log in with Firebase by running the command firebase login. Afterward, run the command firebase init functions from your project root directory. The tool will ask some questions that you need to answer. Iโ€™ll give you an answer workflow example.

  • Are you ready to proceed? โ†’ Yes
  • Please select an option: โ†’ Use an existing project
  • What language would you like to use to write Cloud Functions? โ†’ JavaScript
  • Do you want to use ESLint to catch probable bugs and enforce style? โ†’ No
  • Do you want to install dependencies with npm now? โ†’ Yes

After successful completion, you will find a new functions folder in your project structure.

Screenshot of functions folder after initialization by author
Screenshot of functions folder after initialization by author

The next step is to write the actual code that will be executed in the cloud.

Writing a cloud function

Our demonstration code will be a function that expects a string as an argument and converts the input into upper case. Itโ€™s very simple but it should give you an idea of what you can do and how you can achieve it.

We open the index.js in the functions folder and write the following code:

We define a callable method called toUpperCase with two parameters. data contains the string we want to transform and the second parameter is a CallableContext that we wonโ€™t need in this example. Then we use the built-in toUpperCase method of JavaScript and return the result. Easy as that!

๐Ÿ’ก

Tip

Your code should be idempotent! This means it produces the same result even when it is invoked multiple times. Make sure to stick to that pattern because it will allow you to retry failed executions very easily.

๐Ÿ’ก

Tip

You can also use TypeScript or Python as a programming language.

Deploying a cloud function

Deployment is pretty simple, just run the command firebase deploy --only functions and wait for the process to finish. It can take up to 5 minutes till your dashboard is updated. The dashboard also provides information about logs and the utilization of your functions.

Screenshot of Firebase functions dashboard by author
Screenshot of Firebase functions dashboard by author

Calling a cloud function

A callable function can be identified by the onCall((request) => {...}); method. The Firebase dashboard doesnโ€™t distinguish between callable functions and HTTP endpoints, both triggers show โ€œRequestโ€ as a type. To call a function with the name toUpperCase(), have a look at the following code example:

HTTP request endpoint

With the code onRequest((request, result) โ‡’ {...}); you can define an HTTP endpoint that other web services can call on demand. That way you can define interfaces for 3rd party software to operate with your data or logic. You donโ€™t even need the Firebase package to call endpoints, but something to create requests like http or Dio. Have a look at the example code:

๐Ÿ’ก Tip

You need to replace the link to the function with your deployed version!

I also created an article with demo code on how to create and send HTTP requests in Flutter that might be helpful if you are not familiar with the topic.

โ—

Warning

A HTTP endpoint can be accessed by anyone by default. Make sure to implement safety measures like an authorization token. Click here for an official example of how to secure your endpoints.

Scheduling a function

It is also possible to schedule the execution of a function. The interval or timeframe can either be described with the App Engine cron.yaml syntax or with the good old Unix crontab syntax. The following code example defines a function that is executed every 10 minutes.

The next example works with Unix crontab syntax and defines a timezone. Click here for a list of all supported timezones.

Regions

Firebase uses different regions that affect pricing and latency. You can specify your desired region with the region property and a valid region name as a parameter. It works similar to the time zone and schedule properties in the earlier code examples. Example: region: โ€europe-west3โ€. Click here for a list of all available regions. I recommend using the nearest region to your location. You can also pass multiple regions separated by commas to the function.

Logging

To monitor the execution of functions, you can use logging. The output will be visible in your Firebase Functions dashboard.

const { log, info, debug, warn, error, write } = require("firebase-functions/logger");

log("log:", someObj); 
info("info:", someObj); 
debug("debug:", someObj); 
warn("warn:", someObj);
error("error:", someObj);
write("write:", someObj);

Further details about logging can be found in the official documentation.

onCall() or onRequest()?

Callable functions and HTTP functions are quite similar. A callable function is an HTTP function with special request parameters. The main differences are that authentication tokens for Firebase and Firebase Cloud Messaging as well as App Check tokens are automatically included in the request if available. In addition, a callable function validates these tokens by default. This means you get authentication features for free if you use the onCall() method of the Cloud Functions package.

As stated before, HTTP functions donโ€™t have any access control features integrated by default. You have to do it on your own. But it is also true that you can execute a callable function with an HTTP request if you provide the correct data. For further details, read the documentation here.

โœ… Go with callable functions if your app is the only consumer

โœ… Go with HTTP functions if you have 3rd party consumers (for example a public REST API) but make sure to implement access control and other security mechanisms.

Conclusion

In this article, I showed you how to work with Firebase Cloud Functions in Flutter apps in the most simple way. Firebase Cloud Functions provide an easy way to use external computation power in your Flutter app. Here is a short demo video of the source code.

Firebase Cloud Functions demo by author
Firebase Cloud Functions demo by author

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

Additional resources

Here are some additional resources about Firebase in case you want to dive deeper into the topic.

Firebase Cloud Functions

Your all-in-one toolbox to building serverless infrastructures in the cloud. Write once and scale to infinity!

Firebase Cloud Storage

Upload and download user-generated content like on a file system. Firebase Cloud Storage makes file handling simple!

Firebase Remote Config

Real-time feature toggles or A/B testing are typical use cases of Firebase Remote Config. Learn how to implement them now!

Firebase Console

Learn how to manage projects, apps, users, billing plans, and costs with step-by-step guides in the Firebase Console.

Firebase Cloud Firestore

Learn about Firebase Firestore and write mobile apps with the power of a modern and fast NoSQL database.

Firebase Authentication

Implement email/password authentication or use social providers like Google, Microsoft, and Facebook for your apps!

Firebase Hosting

Host your web apps, microservices, dynamic, and static content with this powerful yet simple solution from Firebase!