1 | initial version |
The process of invoking a Cloud Function in Firebase through Flutter involves the following steps:
Set up your Flutter project and integrate Firebase into your app.
Create a Cloud Function in Firebase Console or deploy it using Firebase CLI.
Write a function in Flutter to call the Cloud Function. You can use the FirebaseFunctions
class from the firebase_functions
package and initialize it using FirebaseFunctions.instance
, which returns a singleton instance. Then, you can call the Cloud Function using the httpsCallable
method of the FirebaseFunctions
class.
Pass the necessary parameters to the Cloud Function using a Map
object.
Handle the response of the Cloud Function in your Flutter code.
Here is an example of how you can call a Cloud Function named addNumbers
in Flutter:
import 'package:firebase_functions/firebase_functions.dart';
final functions = FirebaseFunctions.instance;
Future<int> addNumbers(int a, int b) async {
final httpsCallable = functions.httpsCallable('addNumbers');
final result = await httpsCallable.call({
'a': a,
'b': b,
});
return result.data;
}
This function takes two integers a
and b
as parameters, calls the Cloud Function addNumbers
with these parameters, and returns the result of the Cloud Function as an integer. You can use this function in your Flutter code like this:
int result = await addNumbers(3, 4);
print(result); // prints 7
Note that you need to handle errors that may occur while calling the Cloud Function. The call
method of the FirebaseFunctions.HttpsCallable
class returns a HttpsCallableResult
object that has a data
property containing the result of the Cloud Function. However, the call
method may throw an exception if the Cloud Function fails to execute. You can handle these exceptions using a try-catch
block.