Harnessing Cloud Functions in Your Flutter Application
Written on
In this article, I will illustrate how to create and deploy a cloud function using Firebase, and how to invoke it from a Flutter application.
This article contains outdated information. For the latest version, click here!
Firebase Cloud Functions is a Google service that allows you to execute code in the cloud. Its significant advantage lies in scalability; if your application experiences high user traffic, Firebase can manage it without causing delays. The main topics of this article include:
- Configuring Firebase and your application
- Initializing cloud functions
- Developing a cloud function
- Deploying a cloud function
- Invoking a cloud function
- Using functions as HTTP request endpoints
- Scheduling functions
- Selecting regions
- Logging
Would you like more comprehensive details? Check out my ebook for extensive guides on building Flutter applications with Firebase! Purchase it on Gumroad today!
Configuring Firebase and Your Application
First, set up Firebase and link it to your application. Refer to the following article for detailed instructions.
How to Create a Firebase Project and Link It with Your Flutter App
In this article, I will guide you through the process of creating a Firebase project and linking it to your Flutter application.
levelup.gitconnected.com
The next step involves installing the Firebase Cloud Functions package. You can either add it to your pubspec.yaml file or use the command line. For further guidance, consult the installation manual or the following article.
How to Install Packages in Your Flutter App
This brief article demonstrates how to add packages to a Flutter application to utilize existing code and enhance development speed.
xeladu.medium.com
With the setup complete, you are ready to begin writing your functions.
Initializing Cloud Functions
Authenticate with Firebase by executing the command firebase login. Then, from your project root directory, run the command firebase init functions. The tool will prompt you with several questions that you'll need to answer. Here’s an example workflow:
- Are you prepared to continue? Yes
- Please choose an option: Use an existing project
- Which language would you like to use for Cloud Functions? JavaScript
- Would you like to use ESLint for bug detection and style enforcement? No
- Do you want to install dependencies with npm now? Yes
Once completed successfully, a new functions folder will appear in your project structure.
Now, it’s time to write the code that will execute in the cloud.
Developing a Cloud Function
For demonstration purposes, our function will take a string argument and convert it to uppercase. Although simple, it will provide insight into what can be accomplished.
Open the index.js file in the functions folder and enter the following code:
We define a callable method named toUpperCase with two parameters: data (the string to transform) and a CallableContext, which won’t be necessary for this example. We then utilize JavaScript's built-in toUpperCase method and return the outcome. Simple, isn’t it?
Ensure your code is idempotent! This means it should yield the same result even when invoked multiple times, allowing for easy retries of failed executions.
You may also opt to use TypeScript as your programming language; just remember to select “TypeScript” during initialization instead of “JavaScript.” Currently, no other languages are supported.
Deploying a Cloud Function
Deployment is straightforward; simply execute the command firebase deploy --only functions and wait for the process to complete, which may take up to five minutes for your dashboard to refresh. The dashboard will also show logs and function usage details.
Invoking a Cloud Function
A callable function is identified by the method functions.http.onCall((data, context) => {...});. The Firebase dashboard does not differentiate between callable functions and HTTP endpoints; both are categorized as “Request.” To invoke a function named toUpperCase(), consider the following code example:
HTTP Request Endpoint
Using the code functions.https.onRequest((request, result) => {...});, you can create an HTTP endpoint that other web services can call as needed. This allows you to define interfaces for third-party software to interact with your data or logic. Note that you don’t require the Firebase package to call endpoints; a tool for creating requests, such as http or Dio, is sufficient. Here’s an example code snippet:
Make sure to replace the link to the function with your deployed version! The `<server>` and `<projectId>` are placeholders.
I have also created an article with demo code on how to create and send HTTP requests in Flutter, which may be useful if you're unfamiliar with the topic.
How to Make HTTP Requests with Flutter and Parse JSON Result Data
This brief article outlines how to perform HTTP requests from a Flutter application, covering common scenarios.
levelup.gitconnected.com
HTTP endpoints are accessible by anyone by default. Be sure to implement security measures, such as an authorization token. Click here for an official example on securing your endpoints.
Scheduling a Function
You can also schedule a function's execution. The interval can be specified using the App Engine cron.yaml syntax or the traditional Unix crontab syntax. The following code snippet defines a function that runs every ten minutes.
The next example utilizes Unix crontab syntax and specifies a timezone. Click here for a comprehensive list of all supported timezones.
Regions
Firebase operates in various regions that influence pricing and latency. You can set your desired region using the region() method along with a valid region name as a parameter. For example: functions.region("europe-west3"). Click here for a list of all available regions. It’s advisable to choose the region closest to your location. You can also specify multiple regions, separated by commas.
Logging
To track 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 log:", someObj); functions.logger.info("This is info:", someObj); functions.logger.warn("This is warn:", someObj); functions.logger.error("This is error:", someObj);
For more details on logging, please refer to the official documentation.
onCall() or onRequest()?
Callable functions and HTTP functions are quite similar. A callable function is essentially an HTTP function with specific request parameters. The main distinctions are 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, offering authentication features at no cost when using the onCall() method.
Conversely, HTTP functions lack integrated access control features; you must implement them yourself. However, you can execute a callable function via an HTTP request if you supply the correct data. For further information, refer to the documentation here.
- Use callable functions if your application is the only consumer.
- Opt for HTTP functions if you have third-party consumers (for instance, a public REST API), ensuring you incorporate access control and other security measures.
Conclusion
Firebase Cloud Functions present a convenient method to leverage external computation power within your Flutter app. Here’s a brief demo video showcasing the source code.
You can find the complete example source code on my GitHub page.
GitHub - xeladu/flutter_firebase
This repository contains the companion app for the Flutter Firebase Compendium, featuring code examples. The Flutter Firebase Compendium is an extensive resource for developers.
github.com
This article is part of the Flutter Firebase Compendium, which includes numerous tutorials and guides on utilizing Firebase in conjunction with Flutter applications.
Discover the Potential of Flutter and Firebase
Learn about the capabilities of Flutter and Firebase at:
xeladu.medium.com
Maximize your use of Firebase for Flutter development with my ebooks.
The Flutter Firebase Compendium
This ebook aims to facilitate the integration of Firebase cloud services within your applications, serving as a quick-start guide for developers.
xeladu.gumroad.com
Firebase Cloud Functions
Updated for 2023! Firebase Cloud Functions is a Google service that allows you to run code in the cloud efficiently.
xeladu.gumroad.com
Flutter Articles for Beginners
Explore articles and tutorials that cover essential knowledge every Flutter developer should possess.
xeladu.medium.com
Advanced Flutter Topics for Software Engineers
Delve into advanced topics for Flutter developers, including testing, Firebase, tooling, and more.
xeladu.medium.com