flutter_lwa 0.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 83

flutter_lwa #

pub package Build Status Coverage Status

A Flutter plugin for using Login with Amazon on Android and iOS.

Installation #

In addition to adding a pubspec dependency, this plugin requires Login with Amazon setup which requires modification of the native Android and iOS code of your flutter application.

Add a dependency to your pubspec.yml file #

See the installation instructions on pub.

Login with Amazon #

Register for Login with Amazon access and create API keys for Android and iOS as described in the documentation.

Android #

  1. Create a Login with Amazon API key for Android.

  2. Create a text file located at {project_root}/android/app/main/assets/api_key.txt

  3. Copy-paste the contents of the API key from the Login with Amazon console into the file {project_root}/android/app/main/assets/api_key.txt

Done!

iOS #

  1. Create a Login with Amazon API key for iOS.

  2. Add the APIKey key to the iOS properties file located at {project_root}/ios/Runner/Info.plist. The {api_key} should be the API key copy-pasted from the Login with Amazon console.

	<key>APIKey</key>
	<string>{api_key}</string>
  1. Add the CFBundleURLTypes key to the iOS properties file located at {project_root}/ios/Runner/Info.plist. The {bundle_id} should be the bundle identifier of your application. (Example of a bundle id: com.github.ayvazj.example)
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleURLName</key>
			<string>{bundle_id}</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>amzn-{bundle_id}</string>
			</array>
		</dict>
	</array>
  1. Update {project_root}/ios/Runner/AppDelegate.m to add the #import <LoginWithAmazon/LoginWithAmazon.h> import statement as well as the (BOOL)application:(UIApplication *)application openURL:(NSURL *) url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options method.

#import <LoginWithAmazon/LoginWithAmazon.h>

@implementation AppDelegate

...

- (BOOL)application:(UIApplication *)application openURL:(NSURL *) url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    return [AMZNAuthorizationManager handleOpenURL:url
                                 sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}

...

@end

A sample of a complete Info.plist file can be found here.

Done!

How do I use it? #

The plugin follows the same patterns as the Google Signin API to make integration simple. For a complete sample see the example application.

import 'package:flutter_lwa/lwa.dart';

LoginWithAmazon _loginWithAmazon = LoginWithAmazon(
  scopes: <Scope>[ProfileScope.profile(), ProfileScope.postalCode()],
);

class _MyAppState extends State<MyApp> {
  LwaAuthorizeResult _lwaAuth;

  @override
  void initState() {
    super.initState();
    _loginWithAmazon.onLwaAuthorizeChanged.listen((LwaAuthorizeResult auth) {
      setState(() {
        _lwaAuth = auth;
      });
    });
    _loginWithAmazon.signInSilently();
  }

  Future<void> _handleSignIn(BuildContext context) async {
    try {
      await _loginWithAmazon.signin();
    } catch (error) {
      if (error is PlatformException) {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("${error.message}"),
        ));
      } else {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(error.toString()),
        ));
      }
    }
  }

  Future<void> _handleSignOut() => _loginWithAmazon.signOut();
}

0.1.0 #

  • Initial release.

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_lwa/lwa.dart';

LoginWithAmazon _loginWithAmazon = LoginWithAmazon(
  scopes: <Scope>[ProfileScope.profile(), ProfileScope.postalCode()],
);

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

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

class _MyAppState extends State<MyApp> {
  LwaAuthorizeResult _lwaAuth;
  LwaUser _lwaUser;

  @override
  void initState() {
    super.initState();
    _loginWithAmazon.onLwaAuthorizeChanged.listen((LwaAuthorizeResult auth) {
      setState(() {
        _lwaAuth = auth;
      });
      _fetchUserProfile();
    });
    _loginWithAmazon.signInSilently();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> _fetchUserProfile() async {
    if (_lwaAuth != null && _lwaAuth.isLoggedIn) {
      _lwaUser = await _loginWithAmazon.fetchUserProfile();
    } else {
      _lwaUser = null;
    }
    setState(() {
      _lwaUser = _lwaUser;
    });
  }

  Future<void> _handleSignIn(BuildContext context) async {
    try {
      await _loginWithAmazon.signin();
    } catch (error) {
      if (error is PlatformException) {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("${error.message}"),
        ));
      } else {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(error.toString()),
        ));
      }
    }
  }

  Future<void> _handleSignOut() => _loginWithAmazon.signOut();

  @override
  Widget build(BuildContext context) {
    debugPaintSizeEnabled = false;
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text(
              'Sample Login with Amazon App',
            ),
          ),
          body: Builder(
            builder: (BuildContext _context) {
              return isLoading ? _loadingView : _bodyView(_context);
            },
          )),
    );
  }

  bool get isLoading {
    return false;
  }

  Widget get _loadingView {
    return new Center(
      child: new CircularProgressIndicator(),
    );
  }

  Widget _bodyView(BuildContext context) {
    return _lwaUser != null && _lwaAuth.isLoggedIn
        ? _loggedInWidgets()
        : _loggedOutWidgets(context);
  }

  Widget _loggedInWidgets() {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Container(
        padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
        child: Align(
            alignment: Alignment.topRight,
            child: FlatButton(
              child: Text('Logout'),
              onPressed: _handleSignOut,
            )),
      ),
      Expanded(
        child: Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
            child: Text(
              "Welcome, ${_lwaUser.userName}!\nYour email is ${_lwaUser.userEmail}\nYour zipCode is ${_lwaUser.userPostalCode}\n",
              maxLines: 6,
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    ]);
  }

  Widget _loggedOutWidgets(BuildContext context) {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Expanded(
        child: const Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
            child: Text(
              'Welcome to Login with Amazon!\nIf this is your first time logging in, you will be asked to give permission for this application to access your profile data.',
              maxLines: 6,
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
      Container(
        padding: EdgeInsets.fromLTRB(0, 10, 0, 30),
        child: LwaButton(onPressed: () => _handleSignIn(context)),
      ),
    ]);
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_lwa: ^0.1.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_lwa/generated/i18n.dart';
import 'package:flutter_lwa/lwa.dart';
import 'package:flutter_lwa/scope.dart';
import 'package:flutter_lwa/widgets.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
66
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
83
Learn more about scoring.

We analyzed this package on Jun 4, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.2
  • pana: 0.13.8-dev
  • Flutter: 1.17.1

Health suggestions

Fix lib/lwa.dart. (-0.50 points)

Analysis of lib/lwa.dart reported 1 hint:

line 292 col 10: The declaration 'isCanceled' isn't referenced.

Format lib/generated/i18n.dart.

Run flutter format to format lib/generated/i18n.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test