Connecting to AWS AppSync using Amplify for Flutter for our Football Match Center
Tags: allgemein, community, flutter, serverless
Published: 2023-03-27 22:40:19

---
title: Connecting to AWS AppSync using Amplify for Flutter for our Football Match Center
published: true
date: 2023-03-27 22:34:26 UTC
tags: Allgemein,Community,Flutter,Serverless
canonical_url: https://lockhead.info/index.php/2023/03/28/connecting-to-aws-appsync-using-amplify-for-flutter-for-our-football-match-center/
---

![](https://lh4.googleusercontent.com/TUT-N9z-Y4xfMe_xEzoSBf8YcrPrrUueInu-0cYjRGiYSEnbdTyxUGGW-bFne64V4WaXgAhqsuDHsQiiUEUwiHdb8G_-mIpYCYguxsLQSOjRxFxhCS99I9jfS_b1D3eOLn871IGCIlZp0SLSzsaQisE)

In the last weeks – or already months – I’ve been working together with Christian, also an AWS Community Builder, on our project named “Football Match Center”. Christian has already been writing a lot about our project on LinkedIn:

1. [Project announcement](https://www.linkedin.com/posts/christian-bonzelet_the-last-weeks-was-a-bit-quite-here-on-my-activity-7033719479888945152-Bf5H/?utm_source=share&utm_medium=member_desktop)
2. [Polling](https://www.linkedin.com/posts/christian-bonzelet_in-my-recent-post-i-highlighted-some-options-activity-7036303607943593985-lFUD/?utm_source=share&utm_medium=member_desktop) 
3. [Choosing our API](https://www.linkedin.com/posts/christian-bonzelet_fmc-awscommunity-activity-7034439218210701312-EM9m?utm_source=share&utm_medium=member_desktop)

Today, I want to put the attention on our chosen framework for the UI and the way that we are connecting from the UI to the backend. Our backend in this project is a GraphQL API endpoint hosted on AWS AppSync.

# Building our UI in Flutter

Since [last year](https://aws.amazon.com/blogs/mobile/announcing-flutter-web-and-desktop-support-for-aws-amplify-storage-analytics-and-api-libraries/) Amplify Flutter includes support for Web and Desktop. As we are looking to reach users both on mobile as also on the desktop, choosing a cross-platform development tool like [Flutter](https://flutter.dev/) seemed to be an obvious choice. Christian and I are a small team, and we want to focus on building a simple UI quickly without the need to implement for multiple platforms and Flutter allows exactly that.

Flutter provides easily extendable widgets that can be used on all major platforms.

## Connecting to our GraphQL backend

![](https://lh5.googleusercontent.com/PtT5pHBviAhduODWtRlrFdHM3ofEdxzyMJbHiYdgbyDn-uM3VLQkeKODZT2oCCjIopBqguyNUout6B30vQ17afUx0--CVu419gYr7qOkMwWdgQK3j2xGg5qG-zn20eA0L4J3kItWaVd2q_LSkVTDRdY)

Our project is not based on an Amplify backend, but on AWS infrastructure written in AWS CDK. This made it rather difficult to use the [Amplify Flutter SDK](https://docs.amplify.aws/lib/q/platform/flutter/) as most of the documentations and [blog posts](https://aws.amazon.com/getting-started/hands-on/build-flutter-mobile-app-part-one/module-three/) expect you to connect the Amplify SDK with an Amplify backend (which can then include a GraphQL API).

But that’s not only what made it difficult – I also had very little experience with Amplify or the Amplify SDK when starting to work on the connection.

Using the Flutter SDK for Amplify we will be connecting to our Cognito instance for Authentication and to our existing GraphQL endpoint. In this post I am going to look at the GraphQL connection and not on the integration of Cognito as an authentication endpoint.

Setting up Amplify SDK for Flutter can be done through the [amplify cli](https://docs.amplify.aws/lib/project-setup/create-application/q/platform/flutter/#1-create-a-new-project) if you are starting a new project.

This will then also create the required amplifyconfiguration.dart and some example code through amplify init.

You can then set up the Amplify SDK for Flutter from within your main widget using this code:

```
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_api/amplify_api.dart';
import 'amplifyconfiguration.dart';
import 'models/ModelProvider.dart';

….

 Future<void> _configureAmplify() async {
    final api = AmplifyAPI(modelProvider: ModelProvider.instance);
    await Amplify.addPlugin(api);
    await Amplify.configure(amplifyconfig);
    try {
      await Amplify.configure(amplifyconfig);
    } on AmplifyAlreadyConfiguredException {
      safePrint(
          'Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
    }
  }
```

While this looks easy when reading the documentation (and a lot of very good blog posts), this was rather difficult for me as I was not able to use the amplify init command. Finding out the structure of the “amplifyconfiguration.dart” and the implementation for the “ModelProvider” were my main challenges.

Lately, the [related documentation](https://docs.amplify.aws/lib/graphqlapi/existing-resources/q/platform/flutter/) has been updated and it is now easier to work with existing resources.

### The Amplify Configuration file

The Amplify Configuration (amplifyconfiguration.dart) configures all of the required Amplify Plugins. In our implementation we started with the GraphQL backend:

```
const amplifyconfig = """{
"UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "api": {
        "plugins": {
            "awsAPIPlugin": {
                "matchcenter": {
                    "endpointType": "GraphQL",
                    "endpoint": "https://xxxx.appsync-api.eu-central-1.amazonaws.com/graphql",
                    "region": "eu-central-1",
                    "authorizationType": "API_KEY",
                    "apiKey": "xx0-3425ddregsGDE42dfw"
                }
            }
        }
    }
}""";
```

This tells  the Amplify SDK to talk to a specific API endpoint when the “[Amplify.API](https://docs.amplify.aws/lib/graphqlapi/query-data/q/platform/flutter/#list-subsequent-pages-of-items)” is invoked. As far as I understand [this Github issue](https://github.com/aws-amplify/amplify-category-api/issues/225), right now only one API can be queried from a specific Amplify instance. 

When using the apiKey to do the authentication with the API, we will need to regularly update the Flutter application as the default API [expires after 7 days](https://docs.aws.amazon.com/appsync/latest/APIReference/API_ApiKey.html).

This documentation was not available when we started to work on the project and I have the suspicion that [Salih](https://www.linkedin.com/in/salihgueler/) made this happen 🙂 (if not, still THANKS for the help you gave me! 🙂)

### The ModelProvider

The ModelProvider should be a generated file, which you can generate from an existing GraphQL API. If you are using a schema that is not managed by Amplify, you will need to use “[amplify codegen](https://docs.amplify.aws/cli/graphql/client-code-generation/#amplify-codegen-statements)” based on an existing schema file. 

The command expects a schema.graphql to be available in the “root” folder of the Amplify Flutter project. If you execute “amplify codegen models”, required Dart files will be generated in the “lib/models” directory.

The result should be a file similar to this one:

```
import 'package:amplify_core/amplify_core.dart';
import 'Match.dart';
import 'PaginatedMatches.dart';
import 'PaginatedTeams.dart';
import 'Team.dart';
export 'Match.dart';
export 'PaginatedMatches.dart';
export 'PaginatedTeams.dart';
export 'Team.dart';

class ModelProvider implements ModelProviderInterface {
  @override
  String version = "4ba35f5f4a47ee16223f0e1f4adace8d";
  @override
  List<ModelSchema> modelSchemas = [Match.schema, PaginatedMatches.schema, PaginatedTeams.schema, Team.schema];
  static final ModelProvider _instance = ModelProvider();
  @override
  List<ModelSchema> customTypeSchemas = [];
  static ModelProvider get instance => _instance;
  ModelType getModelTypeByModelName(String modelName) {
    switch(modelName) {
      case "Match":
        return Match.classType;
      case "PaginatedMatches":
        return PaginatedMatches.classType;
      case "PaginatedTeams":
        return PaginatedTeams.classType;
      case "Team":
        return Team.classType;
      default:
        throw Exception("Failed to find model in model provider for model name: " + modelName);
    }
  }
}
```

## Querying our GraphQL API

Now that we have been able to connect to our GraphQL AWS AppSync endpoint, we can start querying data.

Luckily, the preparations we made and the [Amplify for Flutter SDK](https://docs.amplify.aws/lib/graphqlapi/query-data/q/platform/flutter/) provides convenience methods that returned typed data structures that we can directly interact or work with.

You only need to write the GraphQL query that you are interested in and you can directly read data from the endpoint. In my example below I’m creating a Flutter Widget out of the returned elements and then I am adding them to a list of Widgets that I can display in a [Column](https://api.flutter.dev/flutter/widgets/Column-class.html) Widget:

```
Future<List<TeamWidget>> _getMatchesByCountry(String country) async {
    List<TeamWidget> teamsWidgetList = [];
    try {
      String graphQLDocument = '''query ListTeams {
        getTeamsByCountry(country: "${country}") {
            nextToken
            teams {
              PK
              PrimaryColor
              SK
              SecondaryColor
              TeamName
            }
          }
        }''';
      var operation = Amplify.API
          .query(request: GraphQLRequest<String>(document: graphQLDocument));
      var response = await operation.response;
      var data = response.data;
      if (data != null) {
        Map<String, dynamic> userMap = jsonDecode(data);
        List<dynamic> matches = userMap["getTeamsByCountry"]["teams"];
        matches.forEach((element) {
          if (element != null) {
            if (element["id"] == null) {
              element["id"] = "rnd-id";
            }
            var match = Team.fromJson(element);
            teamsWidgetList.add(TeamWidget(match));
          }
        });
      }
    } on ApiException catch (e) {
      print('Query failed: $e');
    }
    return teamsWidgetList;
  }
```

It is of course also possible to [create, update or delete data](https://docs.amplify.aws/lib/graphqlapi/mutate-data/q/platform/flutter/).

Just today, we have merged a feature that adds a “[subscription](https://aws.amazon.com/graphql/graphql-subscriptions-real-time/)” to our AppSync endpoint – as as next step we plan to integrate this within the Amplify Flutter Application which will then allow us to implement notifications to the end users. Unfortunately, the Amplify SDK for Flutter does not yet support [in-app messaging](https://docs.amplify.aws/lib/in-app-messaging/overview/q/platform/js/) as it does for Javascript.

# What YOU learned – and what I learned

Through this blog post you have learned how to connect an Flutter application with Amplify using the Flutter SDK for Amplify. You have also got to know our project, the “Football Match Center” – and you’ve seen some code to make your start easier when talking to a GraphQL (AppSync) backend.

I have learned to work with the Amplify for Flutter SDK and also how code generators can help you to speed up your implementation.  I’ve also gained experiences in accessing data from AppSync and on working with the returned data in Flutter.

Unfortunately, I have also found out that using the Flutter SDK for Amplify I can right now not implement the planned in-app notifications that Christian and I wanted to build for our Football Match Center to notify users about upcoming or recently completed games. 

We will need to find a workaround to that and not rely on the Flutter SDK for amplify – rather implement notifications using the [flutter\_local\_notifications](https://pub.dev/packages/flutter_local_notifications) plugin or by using the Firebase [possibility for notification](https://firebase.google.com/codelabs/firebase-fcm-flutter#0).

**Looking forward to hear your feedback if you have any ideas on how to make this happen!**

_In the next post about this project I will look at how we have set up our CI/CD pipeline in Amazon CodeCatalyst for this project!_

Hits: 0