DEV Community

Cover image for Flutter apps with AWS Amplify Backend: Part 1 — Basic Setup
FlutterArticles
FlutterArticles

Posted on • Edited on

Flutter apps with AWS Amplify Backend: Part 1 — Basic Setup

Flutter apps with AWS Amplify Backend: Part 1 — Basic Setup

Firebase has become the de-facto backend solution for Flutter applications because of its ease-of-use. However, the new Amplify Flutter provides an alternative for developers who prefer an AWS backend.

In late August, AWS Amplify announced the release of the developer preview for the Flutter framework. The features provided are not yet ready for production, so don’t ditch Firebase just yet.

What is AWS Amplify?

From the Github repo:

AWS Amplify provides a declarative and easy-to-use interface across different categories of cloud operations. Our default implementation works with Amazon Web Services (AWS), but AWS Amplify is designed to be open and pluggable for any custom backend or service.

So basically, it makes it A LOT easier to use AWS Amplify as a backend to your Flutter applications.

What can we do with Amplify (so far)?

  1. Authentication— Create user authentication experiences with Amazon Cognito

  2. Analytics— Collect analytics data with Amazon Pinpoint

  3. Storage— Store user content with Amazon S3

How can we set this up?

The prerequisites for this tutorial are as follows:

  1. Flutter version 1.20.0 or higher

  2. Node.js v10.0 or higher

  3. npmv5.0 or later

  4. gitv2.14.1 or later

The following tutorial series assumes that you are using Android Studio as your IDE.

Install the Amplify-Flutter Developer Preview version of the Amplify CLI by running:

npm install -g @aws-amplify/cli@flutter-preview
Enter fullscreen mode Exit fullscreen mode

Next, you must create an AWS account and select the ‘free tier’ (unless you are feeling brave).

Add User to IAM

Before going any further, we need to add a new user to AWS Identity and Access Management (IAM) which we will use for the rest of this tutorial.

Navigate to the IAM Portal and select ‘Add User’. Make sure you have selected the proper region (top right).

You will be guided through a series of steps to create your user:

Grant yourself programmatic access and name your project.Grant yourself programmatic access and name your project.

Create a new permissions groupCreate a new permissions group

Create a group with AdministratorAccessCreate a group with AdministratorAccess

Review SettingsReview Settings

User creation SuccessUser creation Success

Keep these two access keys handy, you will need them soon!

Create New Flutter Project

Open your Android IDE, and create a new default Flutter app.

Create a new flutter applicationCreate a new flutter application

Initialize Amplify Project

From the integrated terminal in Android Studio, initialize your Amplify project:

amplify init
Enter fullscreen mode Exit fullscreen mode

This command will guide you through a series of steps to initialize your project. It should look something like this (depending on your region and preferred text editor):

When asked whether you want to set up a new user, select NO since we already did that in the previous step. Use the *accessKeyId *and *SecretAccessKey *you obtained at the end of the user setup to complete this step:

When you are finished with the setup, *amplify *should output:

Amplify Files

Our local application is now connected to the cloud — great work! If you explore your project directory a little bit, you will notice that Amplify has created a few folders and configuration files that are used to manage your project.

New FilesNew Files

The first thing you should know is that your .gitignore has been modified to exclude some of the files that amplify has created:

#amplify
amplify/\#current-cloud-backend
amplify/.config/local-*
amplify/mock-data
amplify/backend/amplify-meta.json
amplify/backend/awscloudformation
build/
dist/
node_modules/
aws-exports.js
awsconfiguration.json
amplifyconfiguration.json
amplify-build-config.json
amplify-gradle-config.json
amplifytools.xcconfig
Enter fullscreen mode Exit fullscreen mode
  • lib/amplifyconfiguration.dart: manages identity and authentication to your cloud project. Contains sensitive information.

  • amplify/backend: contains lots of metadata about your cloud instance and any services you may have enabled (we haven’t enabled anything yet)

In general, you won’t need to modify any of these files yourself — that is the beauty with Amplify — all of the nitty-gritty configurations are done automagically through the amplify cli, pretty cool right?

Configuring our App

Now that all the boring stuff is out of the way — we can start using Amplify in our app. Let’s start with a simple app that doesn’t include any services (authentication, analytics, etc…) but simply configures itself with our cloud instance.

In your **pubspec.yaml **add:

amplify_core: '<1.0.0'
Enter fullscreen mode Exit fullscreen mode

This will give us access to the core Amplify packages. Here is a simple main.dart that will launch an app, connect it to your Amplify cloud instance, and output a message indicating success.

import 'package:amplify_core/amplify_core.dart';
import 'package:flutter/material.dart';

import 'amplifyconfiguration.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
    routes: {},
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // gives our app awareness about whether we are succesfully connected to the cloud
  bool _amplifyConfigured = false;

  // Instantiate Amplify
  Amplify amplifyInstance = Amplify();

  @override
  void initState() {
    super.initState();

    // amplify is configured on startup
    _configureAmplify();
  }

  void _configureAmplify() async {
    if (!mounted) return;

    await amplifyInstance.configure(amplifyconfig);
    try {
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Amplify Core example app'),
            ),
            body: ListView(padding: EdgeInsets.all(10.0), children: <Widget>[
              Center(
                child: Column(children: [
                  const Padding(padding: EdgeInsets.all(5.0)),
                  Text(_amplifyConfigured ? "configured" : "not configured"),
                ]),
              )
            ])));
  }
}
Enter fullscreen mode Exit fullscreen mode

After running our app on an emulated device, if everything worked we should see the following render on our screen:

Congrats! You now have the humble beginnings to a Flutter application with Amplify as a back-end.

If you simply want the code for this tutorial, head over to the gist I set up.

Moving Forward

If you have read this far, thanks! Be sure to follow to get all of the newest information on Amplify Flutter. In the next part of this series, we will be adding AWS Cognito to our project to achieve a nice user sign-up/sign-in experience.

This Series

Part 1: Basic Setup

Part 2: Authentication

Part 3: Analytics

Part 4: Storage

Top comments (4)

Collapse
 
tadas_vaidotas_d1f7365c28 profile image
Tadas Vaidotas

To make this work pubspec.yaml should have the following dependencies

dependencies:
  flutter:
    sdk: flutter
  amplify_core: '<1.0.0'
  amplify_flutter: '<1.0.0'
Enter fullscreen mode Exit fullscreen mode

And the main.dart should look like this

import 'package:amplify_flutter/amplify.dart';
import 'package:flutter/material.dart';
import 'amplifyconfiguration.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
    routes: {},
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // gives our app awareness about whether we are succesfully connected to the cloud
  bool _amplifyConfigured = false;

  @override
  void initState() {
    super.initState();

    // amplify is configured on startup
    _configureAmplify();
  }

  void _configureAmplify() async {
    if (!mounted) return;

    await Amplify.configure(amplifyconfig);
    try {
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Amplify Core example app'),
            ),
            body: ListView(padding: EdgeInsets.all(10.0), children: <Widget>[
              Center(
                child: Column(children: [
                  const Padding(padding: EdgeInsets.all(5.0)),
                  Text(_amplifyConfigured ? "configured" : "not configured"),
                ]),
              )
            ])));
  }
}
Enter fullscreen mode Exit fullscreen mode

Changes to the main.dart file include import change and the way how Amplify is configured after the latest changes to it.

It works for me with these changes, use it at your own risk.

Collapse
 
nickowalcz profile image
nickowalcz

Hello I followed the tutorial exactly until you mentioned github near the end. I copied and pasted main.dart that you gave and typed amplify_core: <'1.0.0' into pubspec.yaml but the amplify package is still not able to be found in main.dart. Does anyone know how to resolve this issue?

Collapse
 
cristia90034779 profile image
Cristian

Since the last update to amplify_core you need to add amplify_flutter: <'1.0.0' as well. More info here github.com/aws-amplify/amplify-flu...

Collapse
 
fadilanuzha profile image
Fadila Nuzha • Edited

Thanks for posting this.

I'm getting this error while trying to configure amplify.

Error: MissingPluginException(No implementation found for method configure on channel com.amazonaws.amplify/core)

I've already tried flutter clear and pub get, nothing worked so far