Flutter – Using Google Cloud Functions with parameters
Tags: flutter, gcp, serverless
Published: 2022-04-19 08:22:02

---
title: Flutter – Using Google Cloud Functions with parameters
published: true
date: 2022-04-18 15:42:06 UTC
canonical_url: https://bartvwezel.nl/flutter/flutter-using-google-cloud-functions-with-parameters/
series: Flutter GCP
tags: Flutter, GCP, Serverless
cover_image: https://bartvwezel.nl/wp-content/uploads/2022/03/0_QaAPI8rxxCcrv96x.png
---

In [the previous blog post](https://bartvwezel.nl/flutter/flutter-calling-a-google-cloud-function/), 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.

```java
    // 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:

```xml
    <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:

```java
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](https://bartvwezel.nl/flutter/flutter-calling-a-google-cloud-function/). 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:

```dart
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.

```dart
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:

```dart
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](https://github.com/Barttje/flutter-gcp-function). If you still have any questions, comments, suggestions, or remarks, please let me know!

The post [Flutter – Using Google Cloud Functions with parameters](https://bartvwezel.nl/flutter/flutter-using-google-cloud-functions-with-parameters/) appeared first on [Barttje](https://bartvwezel.nl).