You are currently viewing Flutter Firebase Cloud Functions Example

Flutter Firebase Cloud Functions Example

Let's say you are building your mobile app with flutter and you need some work done at the server. Yet you do not have the time nor the resources to host PHP or whatever language
servers, secure it and keep it fast to serve your app. Well Firebase Cloud functions could be an easier and cheaper option for you.

What is firebase cloud functions?

It is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

That backend code will be written in JavaScript or TypeScript. It will then be hosted in Google's cloud infrastructure in a managed environment. In that way you don't have to manage or deal with your own servers.

So once you've written your code as functions and they are stored in Google cloud environment, you can make a HTTP request or if you are using something like Flutter, Google servers will listen for events automtacially from your app and run the function in response.

Every function will be running in isolation. The servers will automatically respond to increase or decrease of the load. They do this by scaling the virtual server instances as needed.

Firebase Cloud Functions

In short Firebase Cloud Functions allows you to:

  1. Develop a backend without servers. Create functions that are triggered by Firebase products, such as changes to data in the Realtime Database, new user sign-ups via Auth, and conversion events in Analytics.
  2. Run your mobile backend code without managing servers. Cloud Functions are single-purpose JavaScript functions that are executed in a secure, managed Node.js environment.
  3. Low maintenance and deployment. Deploying your code to Google servers requires just one command.
  4. Keeps your logic private and secure

Implementing Cloud Functions

  1. Set up Cloud Functions - Install the Firebase CLI and initialize Cloud Functions in your Firebase project.
  2. Write functions - Write JavaScript code (or TypeScript code to transpile at deployment) to handle events from Firebase services, Google Cloud services, or other event providers.
  3. Test functions - Use the local emulator to test your functions.
  4. Deploy and monitor - Enable billing for your project and deploy your functions using the Firebase CLI. You can use the Firebase console to view and search through your logs.

Read more about Firebase Cloud Functions here.

Let's look at some examples.

Flutter Cloud Functions Plugin

This is a Flutter plugin to use the Cloud Functions for Firebase API.

You need this plugin to use Cloud functions from a Flutter App.

Step 1: Install Cloud Functions

Start by installing the Cloud Functions plugin. Do that by adding it in your pubspec.yaml as a dependency. You also need to include Firebase Core as follows:

dependencies:
  firebase_core: ^1.4.0
  cloud_functions: ^3.0.0

Then flutter pub get to fetch it.

Step 2: Full Example

Start by importing the cloud_functions.dart in your code, alongside other imports like dart async and dart core, as well as firebase core and material package:

import 'dart:async';
import 'dart:core';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

Next Create a stateful widget called MyApp. This will override the createState() method which will return a _MyAppState object which we are about to create:

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

Now proceed to the _MyAppState by extending the State class:

class _MyAppState extends State<MyApp> {
//...

Define an instance field to hold a list of fruits:

  List fruit = [];

Override the initState():

  @override
  void initState() {
    super.initState();
  }

Override the build() method, returning the MaterialApp:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Firebase Functions Example'),
        ),

Also build a body containing a listview.The listview is created using a listview builder. The builder of the listview will contain the number of items or fruits that the listview will contain, as well as the itemBuilder, that will bring us the context as well as the index of the current item. We then return a listTile which will be showing the current fruit based on the index we've been provided by the itemBuilder

        body: Center(
            child: ListView.builder(
                itemCount: fruit.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${fruit[index]}'),
                  );
                })),

We now build a floating action button and listen to it's click events:

        floatingActionButton: Builder(
          builder: (context) => FloatingActionButton.extended(
            onPressed: () async {

When pressed:

              HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(
                  'listFruit',
                  options: HttpsCallableOptions(
                      timeout: const Duration(seconds: 5)));
              await callable().then((v) {
                setState(() {
                  fruit.clear();
                  v.data.forEach((f) {
                    fruit.add(f);
                  });
                });
              }).catchError((e) {
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text('ERROR: $e'),
                ));
              });
            },
            label: const Text('Call Function'),
            icon: const Icon(Icons.cloud),
            backgroundColor: Colors.deepOrange,

Below is the full code:

main.dart

import 'dart:async';
import 'dart:core';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  List fruit = [];
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Firebase Functions Example'),
        ),
        body: Center(
            child: ListView.builder(
                itemCount: fruit.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${fruit[index]}'),
                  );
                })),
        floatingActionButton: Builder(
          builder: (context) => FloatingActionButton.extended(
            onPressed: () async {
              // See index.js in the functions folder for the example function we
              // are using for this example
              HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(
                  'listFruit',
                  options: HttpsCallableOptions(
                      timeout: const Duration(seconds: 5)));
              await callable().then((v) {
                setState(() {
                  fruit.clear();
                  v.data.forEach((f) {
                    fruit.add(f);
                  });
                });
              }).catchError((e) {
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text('ERROR: $e'),
                ));
              });
            },
            label: const Text('Call Function'),
            icon: const Icon(Icons.cloud),
            backgroundColor: Colors.deepOrange,
          ),
        ),
      ),
    );
  }
}

Reference

Below are the links:

No. Link
1. Download code
2. Browse code

Leave a Reply