DEV Community

Cover image for Building a Login Function with AWS Amplify and Flutter
Yasunori Kirimoto for AWS Community Builders

Posted on

Building a Login Function with AWS Amplify and Flutter

img

I built a login function with AWS Amplify and Flutter πŸŽ‰

I built a login function using AWS Amplify, Amplify UI Components' amplify_authenticator, and Flutter!

Advance Preparation

  • Preparing the Flutter environment
    • Flutter #001 - Installation
    • 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

Creating a Flutter project

First, we need to create a Flutter project.
Flutter #002 - Building the Environment

flutter create amplify_app
Enter fullscreen mode Exit fullscreen mode

img

This completes the creation of the Flutter project.

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]

amplify init
Enter fullscreen mode Exit fullscreen mode

img

img

Add authentication
AWS Amplify #003 - Add Authentication

amplify add auth
Enter fullscreen mode Exit fullscreen mode

img

amplify push
Enter fullscreen mode Exit fullscreen mode

img

This completes the setup of AWS Amplify.

Configuring Flutter

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

Overall configuration

img

pubspec.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
Enter fullscreen mode Exit fullscreen mode

Install the Amplify UI Components package related to "amplify_authenticator."

amplify_auth_cognito: ^0.3.0-0
amplify_authenticator: ^0.1.0-0
amplify_flutter: ^0.3.0-0
Enter fullscreen mode Exit fullscreen mode

/lib

main.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(),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Load the AWS Amplify related things.

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

Set up the AWS Amplify authentication.

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

Configure the UI components.

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

Configure the screen after login.

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

/android/app

build.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"
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

img

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

img

I was able to build the login function with AWS Amplify and Flutter πŸ‘

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 πŸ’‘

Top comments (1)

Collapse
 
avinashdalvi_ profile image
Avinash Dalvi

Very well explained πŸ‘πŸ»