DEV Community

Cover image for Flutter – Calling a Google Cloud Function
Bart van Wezel
Bart van Wezel

Posted on • Originally published at bartvwezel.nl on

Flutter – Calling a Google Cloud Function

Most examples of calling a cloud function are using Firebase. With Firebase it is easy to write and maintain your cloud functions. Especially if you are using other functionalities that Firebase offers. However, there is a limitation on the languages you can use to write your cloud functions. With Firebase it is only possible to write your functions in Javascript or Typescript. Luckily it is not that hard to call the cloud functions directly.

Creating the Google Cloud Function

For this example, I will use a simple cloud function. This cloud function returns ‘Hello world!’. In the next blog post, I will go into more extensive use cases for cloud functions.

package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;

public class Example implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    BufferedWriter writer = response.getWriter();
    writer.write("Hello world!");
  }
}
Enter fullscreen mode Exit fullscreen mode

If you want a full description of how to deploy this function on the Google Cloud Platform, you can follow the instructions here. There is also an option to guide you while on the console. That shows you the current progress in deploying the cloud function.

Creating the Flutter Application

Now that I have a cloud function let’s call the function. Since the function can be accessed through a HTTP call, I have to install the HTTP package.

flutter pub add http
Enter fullscreen mode Exit fullscreen mode

Now that the HTTP package is installed, I can call the function by using the get method of the HTTP package.

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');
  }
}
Enter fullscreen mode Exit fullscreen mode

That is all that is necessary. Now I can call this method in the initState of a Widget. This will then show the result of the cloud function in a Text Widget.

class BasicGoogleCloudFunctionExample extends StatefulWidget {
  const BasicGoogleCloudFunctionExample({Key? key}) : super(key: key);

  @override
  _BasicGoogleCloudFunctionExampleState createState() => _BasicGoogleCloudFunctionExampleState();
}

class _BasicGoogleCloudFunctionExampleState extends State<BasicGoogleCloudFunctionExample> {
  late Future<String> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = callCloudFunction();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Google Cloud Function - basic',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Google Cloud Function - basic'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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

The post Flutter – Calling a Google Cloud Function appeared first on Barttje.

Top comments (0)