How to start with Flutter, Firebase and Cloud Functions

Stravaros
Stravaros
Nov 23, 2020 · 7 min read
Image for post
Image for post
How to use Cloud Functions in Flutter App?

Welcome to this article about Flutter, Google Firebase, and Google Cloud Functions.

In this article, I will speak about — Firebase Function for a Flutter mobile app. For the past year, there were more and more articles about Function-as-a-Service (Faas) or serverless software. Google Cloud Functions is one implementation of this service. And we will see how we can implement this in a very basic “Hello World” Flutter/Firebase project.

In this article, you must have some knowledge about Flutter. It will develop an Android app one a Linux distribution with Android Studio. But you can easily adjust to your project.

Overview

In this article, we will see these topics:

  • What is Faas?
  • Google Cloud Function
  • Creating and configuration a new Firebase project
  • Integrating Firebase with Flutter
  • Let’s Flutter a little
  • Run the console Firebase
  • Write your first function
  • Enjoy the result

What is Faas?

Image for post
Image for post
Is server less the next evolution ? ©Ippon

Before beginning, we will speak a little about Function-as-a-Service (Faas) or serverless software.

It is a beautiful mainstream concept.

Imagine, you can store a function in the cloud that does anything you want. No server, no VM, no container, just one thing to think about your business code.

It looks elegant. And it has advantages.

  • You just write a function, post it on the cloud. And when some software needs this function. It is awake, runs code and then it finishes.
  • If millions of users use your code at the same time. The millions of instances of our function are called. So it is scalable.
  • You need the new functionality in your software. Very easy to develop and to implement.
  • If you use major cloud companies (Google, Amazon… You know what I mean), you pay as your use. And some companies propose sometimes until 2 million functions call per month. It is very cheap. I know companies run their business without charge.

But Cloud Functions is not the solution to every problem. You have difficulty making a test, moreover, you have less system control. And when a function is not used for a long time, the response time of the first call can take a long time.

So be careful, many experts swear only with cloud function. It depends on your use case.

Google Cloud Functions

When you start a Firebase project, you have just some part of all functionality of Google Cloud. And when you read the Firebase documentation (just here), you have the impression that you can only write a function with Node.js.

But you have a link between your Firebase account and your Google Cloud account. So you can make everything like Broker, Remote Server, Database, and of course Function. But this time, it can be in Node.js, Python, Go, and Java. For more information, see the documentation here.

In our case, we will use Node.js to write our function.

Now, let’s code… Or not, before let’s configure the project.

Creating and configuration a new Firebase project

Prepare yourself, your going to reinvet the wheel
Prepare yourself, your going to reinvet the wheel

To be honest, I would like to create a step-by-step tutorial for creating a Firebase project. But some other people make it better than me. And I hate to reinvent the wheel if it adds no value. Maybe someday, I will write my own.

It is pretty easy just click and copy, paste:

  • Create a flutter app
  • Go to Firebase https://firebase.google.com/
  • Create a new project
  • Configure platform specificity
  • Import configuration in your flutter project

So I will put some link below to help you :

Integrating Firebase with Flutter

I write a lot, I hope you are still focused. OK?

So let’s go !!!!

Image for post
Image for post

Normally you put some dependencies in your pubsec.yaml file and run a flutter pub get to import in your project

Please add make sure you have this dependency (click to see the pub.dev link):

firebase_core

cloud_functions

Image for post
Image for post

At this point, if you compile your Futter app on an Android phone, you can have an error

“The number of method references in a .dex file cannot exceed 64k”

Keep calm and do worry, you can solving it by increasing the minSdkVersion in the app/build.bradle like this :

Another solution can be found in this article.

Let’s Flutter a little

It was a long introduction, but now let talk about our project. For this example, it is a simple “Hello World”.
We want an application with a form. The user writes in this form. Then he can click on a button that sends the content of the form to a Firebase function API. This function sends in response just the text pass in request with a “Hello” before.

Here the code of our application :

The main function
Initialize Firebase

Let’s describe the last method.

We have an Editable Text Form:

body: Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: myController,
),
),

We have a button, this button when we press it calls the fetchPost() method and print the result in a pop-up alert:

floatingActionButton: FloatingActionButton(
onPressed: () async {
await fetchPost();
return showDialog(
context: context,
child: AlertDialog(
title: Text('Alert'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('The answer'),
Text(_response),
],
),
)));
},
child: Icon(Icons.add_alert),
),

The fetchPost() method calls the Cloud Function hello, which we will create in a few moments. It sends in the parameter message the text we write in the Editable Text Form and it sets the response with the Cloud Function response:

//Call of the hello function
HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(
'hello',
options: HttpsCallableOptions(timeout: Duration(seconds: 5)));
fetchPost() async {
try {
final HttpsCallableResult result = await callable.call(
<String, dynamic>{
'message': myController.text,
},
);
print(result.data['response']);
setState(() {
_response = result.data['response'];
});
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
;
}

You can run the application and enjoy the result. But at this point, our Cloud Function does not run.

Image for post
Image for post
A form and a button

Run the console Firebase

First, we need to install the Firebase console (CLI). In a terminal run the following command. We put here the command for a Linux machine. Again you can follow the documentation here for every information.

sudo npm install -g firebase-tools

Then you should authenticate. Please write the command:

firebase login

And create a project repository before running the last command:

firebase init

You should have a prompt like this:

Image for post
Image for post
Congratulation your almost there !!

Select the “functions: Configure and deploy Cloud Functions” with arrow and space bar then press Enter. Select Use an existing project and then your project. After this the CLI will ask you to custom some files firestore.rules and firestore.indexes.json. In this chapter we will pass and use the default one (press Enter). But in a production project, you must take time on it for performance and security.

Write your first function

You have to open the index.js in the functions repository. Then write your function. In this case, it is simple. We pick the message from the input data. And create a response with a “hello” just before.

To finish, you need to deploy your Firebase function with this command.

firebase deploy --only functions

Enjoy the result

Now, you can test. If you go on our application, you enter something in TextField and click and the FloatingActionButton. You will send to your Firebase Function the content of the TextField. In response, we display “hello” + TextField in the AlertDialog.

Image for post
Image for post
Image for post
Image for post

You can also check if your function runs in the Firebase console on the tab Function.

Note, there are several ways to implement a function on Firebase. I used the cloud package, but we can use an URL that is defined when we deploy our method.

The goal was to present the integration of Firebase in Flutter in a simple way. But we can imagine more complex actions: interacting with Firebase, selecting, or updating data…

I hope you enjoyed this presentation. This is my first major article, I hope it was clear. Do not hesitate to give me feedback or ask your questions in a comment.
See you in a future article 🙂🙂🙂

Image for post
Image for post
https://www.twitter.com/FlutterComm

Flutter Community

Articles and Stories from the Flutter Community

Stravaros

Written by

Stravaros

Hi, my name is Stravaros, I am a French Java developer. But behind this professional activy. I am a Flutter discover, mountain lover and boardgame gamer

Flutter Community

Articles and Stories from the Flutter Community

Stravaros

Written by

Stravaros

Hi, my name is Stravaros, I am a French Java developer. But behind this professional activy. I am a Flutter discover, mountain lover and boardgame gamer

Flutter Community

Articles and Stories from the Flutter Community

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store