Flutter – Using Google Cloud Functions with parameters

In the previous blog post, I describe how to call a Google Cloud Function without Firebase. However, the only option was to invoke the function. Most of the time, more complex functions are necessary. This blog post will describe how to pass information to your Google Cloud Function. This can be done in multiple ways.

Creating the Google Cloud Function

First, let’s update the Google Cloud Function. This function should handle the variables. There are two easy ways to take these variables. The values can be passed through the query parameters or the body of the HTTP Call. Of course, when passing the information through the body of the HTTP call, the call should become a POST call instead of a GET call.

    // Check URL parameters for "name" field
    // "world" is the default value
    String name = request.getFirstQueryParameter("name").orElse("world");

You can use the getFirstQueryParameter to retrieve the query parameters of the request. To read the body, you need to get the writer of the request. One way to parse this is by using the Google GSON library. If you are planning on using the same way, you should add the following dependency:

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.8</version>
    </dependency>

Now you can parse the body of the request and access the variables there:

package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

public class Example implements HttpFunction {
  private static final Logger logger = Logger.getLogger(Example.class.getName());

  private static final Gson gson = new Gson();

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    String name = request.getFirstQueryParameter("name").orElse("world");

    try {
      JsonElement requestParsed = gson.fromJson(request.getReader(), JsonElement.class);
      JsonObject requestJson = null;

      if (requestParsed != null && requestParsed.isJsonObject()) {
        requestJson = requestParsed.getAsJsonObject();
      }

      if (requestJson != null && requestJson.has("name")) {
        name = requestJson.get("name").getAsString();
      }
    } catch (JsonParseException e) {
      logger.severe("Error parsing JSON: " + e.getMessage());
    }

    var writer = new PrintWriter(response.getWriter());
    writer.printf("Hello %s!", name);
  }
}

You can follow the instructions here if you want a complete description of deploying this function on the Google Cloud Platform.

Updating the Flutter Application

This explanation starts with the Flutter Application of the previous blog post. The blog post explains how to call the Google Cloud function with the HTTP package. The application works with a Future; thus, the result is only shown when the HTTP call is done. This is the HTTP call:

import 'package:http/http.dart' as http;

Future<String> callCloudFunction() async {
  final response = await http
      .get(Uri.parse('insert-url-of-your-cloud-fuction'));
  if (response.statusCode == 200) {
    return response.body;
  } else {
    throw Exception('Failed to execute function');
  }
}

To call the function with the query parameters, you can add those variables to the GET request URL.

import 'package:http/http.dart' as http;

Future<String> callCloudFunction() async {
  final response = await http
      .get(Uri.parse('insert-url-of-your-cloud-fuction?name=Bart'));
  if (response.statusCode == 200) {
    return response.body;
  } else {
    throw Exception('Failed to execute function');
  }
}

The Google Cloud Function also looks in the body of the request. To include a body in your HTTP call, you should convert the GET method to a POST method. Now, you can send the body the function expects in the following way:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String> callCloudFunction() async {
  final response = await http.post(Uri.parse('insert your url here'),
      body: jsonEncode(<String, String>{
        'name': 'Bart',
      }));
  if (response.statusCode == 200) {
    return response.body;
  } else {
    throw Exception('Failed to execute function');
  }
}

These steps are all that is necessary to call your cloud function with variables! The code of this example is available here on Github. If you still have any questions, comments, suggestions, or remarks, please let me know!

Leave a Reply