Building a Login Function with AWS Amplify and Flutter
Tags: awsamplify, flutter, aws, dart
Published: 2021-12-22 12:03:23

![img](https://day-journal.com/memo/images/try-076_01.png)

<br>

### I built a login function with AWS Amplify and Flutter :tada:  

I built a login function using [AWS Amplify](https://aws-amplify.github.io/docs/), Amplify UI Components' [amplify_authenticator](https://docs.amplify.aws/ui/q/framework/flutter), and [Flutter](https://flutter.dev)!

<br>

### Advance Preparation
- Preparing the Flutter environment  
  - [Flutter #001 - Installation](https://day-journal.com/memo/flutter-001)
    - Flutter v2.8.0
    - Dart v2.15.0
    - Xcode v13.1
    - Android SDK v32.0.0
    - Android Studio v2020.3
    - Visual Studio Code v1.63.0
    - Flutter extension v3.29.0
- Preparing the AWS Amplify environment
  - [AWS Amplify #001 - Installation](https://day-journal.com/memo/aws-amplify-001)
    - node v16.10.0
    - npm v7.24.0

<br>

## Creating a Flutter project

First, we need to create a Flutter project.
[Flutter #002 - Building the Environment](https://day-journal.com/memo/flutter-002)

```shell
flutter create amplify_app
```

![img](https://day-journal.com/memo/images/try-076_02.png)  

This completes the creation of the Flutter project.

<br>

## Setting up AWS Amplify

The next step is to configure AWS Amplify for Flutter and add authentication capabilities.

Configuring AWS Amplify for Flutter
[AWS Amplify #006 - Building the environment [Flutter version]](https://day-journal.com/memo/aws-amplify-006)

```shell
amplify init
```

![img](https://day-journal.com/memo/images/try-076_03.png)  

![img](https://day-journal.com/memo/images/try-076_04.png)  

<br>

Add authentication
[AWS Amplify #003 - Add Authentication](https://day-journal.com/memo/aws-amplify-003)

```sh
amplify add auth
```

![img](https://day-journal.com/memo/images/try-076_05.png)  

```sh
amplify push
```

![img](https://day-journal.com/memo/images/try-076_06.png)  

This completes the setup of AWS Amplify.

<br>

## Configuring Flutter

Finally, we'll write the actual code for the login function.

<br>

### Overall configuration

![img](https://day-journal.com/memo/images/try-076_07.png)

<br>

### pubspec.yaml

```yaml
name: amplify_app
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
    sdk: '>=2.15.0 <3.0.0'

dependencies:
    flutter:
        sdk: flutter

    cupertino_icons: ^1.0.2

    amplify_auth_cognito: ^0.3.0-0
    amplify_authenticator: ^0.1.0-0
    amplify_flutter: ^0.3.0-0

dev_dependencies:
    flutter_test:
        sdk: flutter

    flutter_lints: ^1.0.0

flutter:
    uses-material-design: true
```

<br>

Install the Amplify UI Components package related to "[amplify_authenticator](https://pub.dev/packages/amplify_authenticator)."

```yaml
amplify_auth_cognito: ^0.3.0-0
amplify_authenticator: ^0.1.0-0
amplify_flutter: ^0.3.0-0
```

<br>

/lib

### main.dart

```dart
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_authenticator/amplify_authenticator.dart';
import 'package:amplify_flutter/amplify.dart';
import 'package:flutter/material.dart';

import 'amplifyconfiguration.dart';

void main() {
  runApp(const MyApp());
}

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

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _configureAmplify();
  }

  Future<void> _configureAmplify() async {
    try {
      await Amplify.addPlugin(AmplifyAuthCognito());
      await Amplify.configure(amplifyconfig);
    } on Exception catch (e) {
      print('Could not configure Amplify: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      home: Authenticator(
        child: const LoggedInScreen(),
      ),
    );
  }
}

class LoggedInScreen extends StatelessWidget {
  const LoggedInScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: const [
            Text('Logged In'),
            SignOutButton(),
          ],
        ),
      ),
    );
  }
}
```

<br>

Load the AWS Amplify related things.

```dart
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_authenticator/amplify_authenticator.dart';
import 'package:amplify_flutter/amplify.dart';
import 'amplifyconfiguration.dart';
```

<br>

Set up the AWS Amplify authentication.

```dart
  Future<void> _configureAmplify() async {
    try {
      await Amplify.addPlugin(AmplifyAuthCognito());
      await Amplify.configure(amplifyconfig);
    } on Exception catch (e) {
      print('Could not configure Amplify: $e');
    }
  }
```

<br>

Configure the UI components.

```dart
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      home: Authenticator(
        child: const LoggedInScreen(),
      ),
    );
  }
```

<br>

Configure the screen after login.

```dart
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: const [
            Text('Logged In'),
            SignOutButton(),
          ],
        ),
      ),
    );
  }
```

<br>

/android/app

### build.gradle

```gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.amplify_app"
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
```

<br>

To display the amplify_authenticator on Android, you need to specify the Android SDK version, so select a fixed "minSdkVersion."

```gradle
    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.amplify_app"
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
```

<br>

Run "Run and Debug" in Visual Studio Code and log in after user registration.

![img](https://day-journal.com/memo/images/try-076_00.gif)

<br>

Check to see if the user is registered in the AWS console.

![img](https://day-journal.com/memo/images/try-076_08.png)  

<br>

#### I was able to build the login function with AWS Amplify and Flutter :thumbsup: 

If you want to implement the login function in Flutter, Firebase is often used, but I was able to confirm that it can be implemented with AWS Amplify :bulb: