AWS Amplify Flutter Authentication Login System Code

 

AWS Amplify Flutter Authentication Login System


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

import 'amplifyconfiguration.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
const MyApp({super.key});

@override
State<MyApp> createState() => _MyAppState();
}

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

void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.configure(amplifyconfig);
safePrint('Successfully configured');
} on Exception catch (e) {
safePrint('Error configuring Amplify: $e');
}
}

@override
Widget build(BuildContext context) {
return Authenticator(
// `authenticatorBuilder` is used to customize the UI for one or more steps
authenticatorBuilder: (BuildContext context, AuthenticatorState state) {
switch (state.currentStep) {
case AuthenticatorStep.signIn:
return CustomScaffold(
state: state,
// A prebuilt Sign In form from amplify_authenticator
body: SignInForm(),
// A custom footer with a button to take the user to sign up
footer: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Don\'t have an account?'),
TextButton(
onPressed: () => state.changeStep(
AuthenticatorStep.signUp,
),
child: const Text('Sign Up'),
),
],
),
);
case AuthenticatorStep.signUp:
return CustomScaffold(
state: state,
// A prebuilt Sign Up form from amplify_authenticator
body: SignUpForm(),
// A custom footer with a button to take the user to sign in
footer: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Already have an account?'),
TextButton(
onPressed: () => state.changeStep(
AuthenticatorStep.signIn,
),
child: const Text('Sign In'),
),
],
),
);
case AuthenticatorStep.confirmSignUp:
return CustomScaffold(
state: state,
// A prebuilt Confirm Sign Up form from amplify_authenticator
body: ConfirmSignUpForm(),
);
case AuthenticatorStep.resetPassword:
return CustomScaffold(
state: state,
// A prebuilt Reset Password form from amplify_authenticator
body: ResetPasswordForm(),
);
case AuthenticatorStep.confirmResetPassword:
return CustomScaffold(
state: state,
// A prebuilt Confirm Reset Password form from amplify_authenticator
body: const ConfirmResetPasswordForm(),
);
default:
// Returning null defaults to the prebuilt authenticator for all other steps
return null;
}
},
child: MaterialApp(
theme: ThemeData.from(
colorScheme: ColorScheme.fromSwatch(
primarySwatch: Colors.deepPurple,
backgroundColor: Colors.white,
),
).copyWith(
indicatorColor: Colors.deepPurple,
),
builder: Authenticator.builder(),
home: const Scaffold(
body: Center(
child: Text('You are logged in!'),
),
),
),
);
}
}

/// A widget that displays a logo, a body, and an optional footer.
class CustomScaffold extends StatelessWidget {
const CustomScaffold({
super.key,
required this.state,
required this.body,
this.footer,
});

final AuthenticatorState state;
final Widget body;
final Widget? footer;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: SingleChildScrollView(
child: Column(
children: [
// App logo
const Padding(
padding: EdgeInsets.only(top: 32),
child: Center(child: FlutterLogo(size: 100)),
),
Container(
constraints: const BoxConstraints(maxWidth: 600),
child: body,
),
],
),
),
),
persistentFooterButtons: footer != null ? [footer!] : null,
);
}
}

dependencies:
flutter:
sdk: flutter

amplify_flutter: ^1.0.0
amplify_auth_cognito: ^1.0.0
amplify_authenticator: ^1.0.0


The provided Flutter code is a mobile application that incorporates the Amplify framework to handle user authentication. Amplify is a set of tools and services by AWS (Amazon Web Services) designed to simplify the development of scalable and secure cloud-powered applications.

Let's break down the key components and functionalities of the code:

  1. Imports:
    The code starts by importing necessary packages related to Amplify, Flutter, and the application's configuration. These include amplify_auth_cognito for Cognito authentication, amplify_authenticator for the pre-built authentication UI components, and amplify_flutter for overall Amplify configuration.

  2. Main Function and App Initialization:
    The main function initializes the Flutter application by calling runApp and passing an instance of the MyApp widget. The MyApp widget is a stateful widget that, when initialized, calls the _configureAmplify method to set up the Amplify configuration.

  3. Amplify Configuration:
    The _configureAmplify method configures Amplify by adding the Cognito authentication plugin and calling Amplify.configure with the provided configuration from amplifyconfiguration.dart. Any errors during the configuration are caught and printed.

  4. Authentication UI:
    The core of the application is an Authenticator widget. This widget uses the authenticatorBuilder to customize the UI based on the current authentication step. The steps include sign-in, sign-up, confirm sign-up, reset password, and confirm reset password.

  5. Custom Scaffold Widget:
    The CustomScaffold widget is a reusable component that displays a logo, a body, and an optional footer. It is used to structure the various authentication forms and their associated UI elements.

  6. Building UI for Each Authentication Step:

    • For the sign-in step, the UI includes a pre-built sign-in form (SignInForm) and a custom footer with a link to the sign-up step.
    • For the sign-up step, the UI includes a pre-built sign-up form (SignUpForm) and a custom footer with a link to the sign-in step.
    • For the confirm sign-up step, the UI includes a pre-built confirm sign-up form (ConfirmSignUpForm).
    • For the reset password step, the UI includes a pre-built reset password form (ResetPasswordForm).
    • For the confirm reset password step, the UI includes a pre-built confirm reset password form (ConfirmResetPasswordForm).
  7. MaterialApp and Home Screen:
    The root of the widget tree is a MaterialApp. It defines the overall theme of the application and sets the home screen. The home screen is initially a placeholder Scaffold with a centered message indicating that the user is logged in. This screen will be displayed once the authentication process is complete.

  8. Theming:
    The application defines a custom theme using ThemeData and specifies the color scheme with primary and background colors. The Authenticator.builder() is used to wrap the MaterialApp, allowing the authentication UI to overlay the main app content seamlessly.

  9. Conclusion:
    In summary, this Flutter application is structured to handle user authentication through the Amplify framework. It provides a seamless and customizable user interface for various authentication steps and integrates with AWS Cognito for secure and scalable user management. The code showcases best practices in Flutter development, including the use of stateful widgets, asynchronous initialization, and a modular approach to UI components.

Previous Post Next Post