Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ Connecting to AWS AppSync using Amplify for Flutter for our Football Match Center

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Connecting to AWS AppSync using Amplify for Flutter for our Football Match Center


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

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
  2. Polling
  3. Choosing our API

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 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 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

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 as most of the documentations and blog posts 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 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 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โ€ is invoked. As far as I understand this Github issue, 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.

This documentation was not available when we started to work on the project and I have the suspicion that Salih 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โ€ 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 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 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.

Just today, we have merged a feature that adds a โ€œsubscriptionโ€ 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 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 plugin or by using the Firebase possibility for notification.

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

...



๐Ÿ“Œ Connecting to AWS AppSync using Amplify for Flutter for our Football Match Center


๐Ÿ“ˆ 125.72 Punkte

๐Ÿ“Œ Building Robust GraphQL APIs with AWS Amplify and AWS AppSync


๐Ÿ“ˆ 57.69 Punkte

๐Ÿ“Œ Flutter Performance, Flutter Games, Flutter Tooling, & More (#AskFlutter at Flutter Live)


๐Ÿ“ˆ 48.36 Punkte

๐Ÿ“Œ Pipeline strategies for a mono-repo โ€“ experiences with our Football Match Center projects in CodeCatalyst


๐Ÿ“ˆ 43.42 Punkte

๐Ÿ“Œ Pipeline strategies for a mono-repo โ€“ experiences with our Football Match Center projects in CodeCatalyst


๐Ÿ“ˆ 43.42 Punkte

๐Ÿ“Œ Cross-Plattform: Der Support fรผr Flutter in AWS Amplify ist produktionsreif


๐Ÿ“ˆ 38.85 Punkte

๐Ÿ“Œ Cross-Platform Mobile App Prototyping With Flutter and AWS Amplify


๐Ÿ“ˆ 38.85 Punkte

๐Ÿ“Œ Building a Personalized Quiz Game with Flutter, AWS Amplify Gen2, and Amazon Bedrock!


๐Ÿ“ˆ 38.85 Punkte

๐Ÿ“Œ The Amplify Series, Part 5: Uploading and retrieving images with Amplify Storage


๐Ÿ“ˆ 38.28 Punkte

๐Ÿ“Œ Origin of Flutter, Dart 2.0, E-Commerce with Flutter, & More (#AskFlutter at Flutter Live)


๐Ÿ“ˆ 36.27 Punkte

๐Ÿ“Œ Flutter news from GDD China: uniting Flutter on web and mobile, and introducing Flutter 1.9


๐Ÿ“ˆ 36.27 Punkte

๐Ÿ“Œ AWS Amplify: Let's add some unit tests into our pipeline


๐Ÿ“ˆ 35.69 Punkte

๐Ÿ“Œ AWS Amplify and ChatGPT: one way to generate html mock files for our demos ๐Ÿค–


๐Ÿ“ˆ 35.69 Punkte

๐Ÿ“Œ Connecting AWS Lambda with Amazon RDS using AWS CDK and Node.js


๐Ÿ“ˆ 35.36 Punkte

๐Ÿ“Œ Deploy Your First Web App on AWS with AWS Amplify, Lambda, DynamoDB and API Gateway


๐Ÿ“ˆ 34.37 Punkte

๐Ÿ“Œ Cook a Recipe: Create a Web application using AWS Amplify


๐Ÿ“ˆ 31.86 Punkte

๐Ÿ“Œ Why I build Virtual PhotoBooth using AWS Amplify ?


๐Ÿ“ˆ 31.86 Punkte

๐Ÿ“Œ Launching a Static Website using AWS Amplify with CI/CD! v1


๐Ÿ“ˆ 31.86 Punkte

๐Ÿ“Œ AWS fixes 'confused deputy' vulnerability in AppSync


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ AWS AppSync Vuln, Zero-Initialization, HTTP/3 Connections, Thinkst Quarterly - ASW #221


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ Convert REST APIs to GraphQL with AWS AppSync


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ Wrangling GraphQL Data Schemas with AWS AppSync


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ Experts found a vulnerability in AWS AppSync


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ Creating Real-Time Dashboards With AWS AppSync


๐Ÿ“ˆ 30.94 Punkte

๐Ÿ“Œ Flutter Hooks Tutorial: Flutter Animation Using Hooks (useEffect and useAnimationController)


๐Ÿ“ˆ 29.28 Punkte

๐Ÿ“Œ Beginner's Guide: Connecting to Your EC2 Instance Using AWS Systems Manager (SSM)


๐Ÿ“ˆ 27.75 Punkte

๐Ÿ“Œ Facial Recognition Tech To Be Implemented Again At Cardiff-Swansea Football Match โ€“ Expert Reaction


๐Ÿ“ˆ 27.17 Punkte

๐Ÿ“Œ Iran is doing to our networks what it did to our spy drone, claims Uncle Sam: Now they're bombing our hard drives


๐Ÿ“ˆ 26.81 Punkte

๐Ÿ“Œ How to Deploy a Next.js 13 Site with AWS Amplify


๐Ÿ“ˆ 26.76 Punkte

๐Ÿ“Œ CI/CD pipelines with AWS Amplify


๐Ÿ“ˆ 26.76 Punkte

๐Ÿ“Œ Amazon Location Service and AWS Amplify to Use Various Map Library


๐Ÿ“ˆ 26.76 Punkte

๐Ÿ“Œ AWS Amplify, another cool dude for developers to act?


๐Ÿ“ˆ 26.76 Punkte

๐Ÿ“Œ Step by step: Build your first AWS Amplify and React App


๐Ÿ“ˆ 26.76 Punkte

๐Ÿ“Œ Deploy Your Next.js App with AWS Amplify Like a Pro โ€” Itโ€™s Easier Than You Think


๐Ÿ“ˆ 26.76 Punkte











matomo