Ashu
Ashu

Reputation: 97

How to use google cloud functions in flutter?

Now this is the index.js file

import 'dart:math';

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

exports.getRandomNumbers=functions.https.onCall((num){

   const numbers=admin.firestore().collection('RandomNumbers').document('CurrentRandomNumber');
   return numbers.add({
   RandomNumber=new Random().nextInt(10);
   });

});

and the function to do the task

onPressed: (){
                CloudFunctions.instance.getHttpsCallable(

                    functionName: "getRandomNumbers",
                );
              },

Now as you can see I am trying to get a random number and add it to the firestore database but it is nor working neither showing any error. I am using android studio and I have installed all stuff as suggested in official doc.

Upvotes: 1

Views: 1778

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

The Flutter code you shared doesn't actually call the Cloud Function yet. What you have now merely defines a reference to that Cloud Function. To call it, you'd do something like:

final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
    functionName: 'getRandomNumbers',
);
dynamic response = await callable.call();

This is a pretty direct copy from the sample in the documentation on using Cloud Functions in Flutter, so I'd recommend keeping that handy while implementing it.


I noticed that your Cloud Function declaration looks unusual:

exports.getRandomNumbers=functions.https.onCall((num){

The examples in the Firebase documentation follow this pattern:

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

So the arguments are always data and context, and any parameters you pass from your flutter code will be in the data argument.

For your current code it makes no difference, since you're not using any of the arguments, but I do recommend addressing this going forward.

Upvotes: 1

Related Questions