Skip to main content

android_sign_in_kit 0.2.0 copy "android_sign_in_kit: ^0.2.0" to clipboard
android_sign_in_kit: ^0.2.0 copied to clipboard

PlatformAndroid

Google Sign-In, passkeys and saved passwords in one sheet through Android's Credential Manager, with scopes, restore keys and a setup checker.

example/lib/main.dart

import 'package:android_sign_in_kit/android_sign_in_kit.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'demo_server.dart';

/// The Web client ID from Google Cloud Console. Pass yours with
/// `flutter run --dart-define=WEB_CLIENT_ID=1234-abc.apps.googleusercontent.com`,
/// or leave it out if the app has google-services.json.
const webClientId = String.fromEnvironment('WEB_CLIENT_ID');

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Gets the sheets ready, so they open instantly on the first tap, and
  // loads the Google user from the last run.
  await AndroidSignInKit.initialize(
    serverClientId: webClientId.isEmpty ? null : webClientId,
  );
  runApp(const DemoApp());
}

class DemoApp extends StatelessWidget {
  const DemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Android Sign-In Kit',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(colorSchemeSeed: Colors.indigo),
      home: const LoginPage(),
    );
  }
}

/// How the user signed in.
enum Method { google, password, passkey }

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _username = TextEditingController();
  final _password = TextEditingController();
  final _server = DemoPasskeyServer();

  /// Who is signed in, and how. A Google user comes back from the last run.
  String? _user = AndroidSignInKit.currentUser?.email;
  Method? _method = AndroidSignInKit.isSignedIn ? Method.google : null;

  /// The latest Google sign-in of this run, for its details.
  GoogleAccount? _google;
  String? _driveToken;

  /// What picking a saved password does: log in right away, or only fill
  /// the fields and wait for "Log in".
  bool _logInWhenPicked = true;
  bool _showPassword = false;
  bool _busy = false;

  @override
  void dispose() {
    _username.dispose();
    _password.dispose();
    super.dispose();
  }

  void _say(String message, {SnackBarAction? action}) {
    ScaffoldMessenger.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(SnackBar(content: Text(message), action: action));
  }

  /// Runs a call and explains its error. A closed sheet needs no message:
  /// the user chose that.
  Future<void> _run(Future<void> Function() call) async {
    setState(() => _busy = true);
    try {
      await call();
    } on CredentialManagerException catch (e) {
      switch (e.code) {
        case CredentialErrorCode.canceled:
          break;
        case CredentialErrorCode.network:
          _say('No internet connection. Connect and try again.');
        case CredentialErrorCode.noProvider:
          _say(
            'No password manager can save this.',
            action: SnackBarAction(
              label: 'Settings',
              onPressed: AndroidSignInKit.openPasswordSettings,
            ),
          );
        default:
          _say(
            '${e.code.name}: ${e.message}'
            '${e.platformMessage == null ? '' : '\n\n${e.platformMessage}'}',
          );
      }
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  void _signedIn(String user, Method method, {GoogleAccount? google}) =>
      setState(() {
        _user = user;
        _method = method;
        _google = google;
        _driveToken = null;
      });

  /// One sheet with saved passwords, passkeys and Google accounts.
  Future<void> _signIn() => _run(() async {
    final credential = await AndroidSignInKit.signIn(
      passkeyRequestJson: _server.signInOptions(),
    );
    switch (credential) {
      case GoogleAccount account:
        _signedIn(account.email, Method.google, google: account);
      case SavedPassword login:
        _username.text = login.username;
        _password.text = login.password;
        await _logIn();
      case PasskeyCredential passkey:
        _passkeySignedIn(passkey);
      case null:
        break;
    }
  });

  Future<void> _signInWithGoogle({bool button = false}) => _run(() async {
    // No serverClientId needed: initialize() got it.
    final account = await AndroidSignInKit.signInWithGoogle(
      useButtonFlow: button,
    );
    if (account != null) {
      _signedIn(account.email, Method.google, google: account);
    }
  });

  Future<void> _lightweightSignIn() => _run(() async {
    final account = await AndroidSignInKit.attemptLightweightSignIn();
    if (account == null) {
      _say('No returning Google account. Use "Sign in with Google".');
      return;
    }
    _signedIn(account.email, Method.google, google: account);
  });

  Future<void> _signInWithPasskey() => _run(() async {
    final passkey = await AndroidSignInKit.signInWithPasskey(
      _server.signInOptions(),
    );
    if (passkey != null) _passkeySignedIn(passkey);
  });

  void _passkeySignedIn(PasskeyCredential passkey) {
    final user = _server.signIn(passkey.responseJson);
    if (user == null) {
      // The server doesn't know this passkey: tell the password manager,
      // so it stops offering it.
      AndroidSignInKit.signalUnknownPasskey(
        rpId: DemoPasskeyServer.rpId,
        credentialId: passkey.credentialId!,
      );
      _say(
        "The demo server doesn't know this passkey (it forgets them when the "
        'app restarts). Log in with the password and create a new one.',
      );
      return;
    }
    _signedIn(user, Method.passkey);
  }

  Future<void> _createPasskey() => _run(() async {
    final user = _user!;
    final registration = await AndroidSignInKit.createPasskey(
      _server.registrationOptions(user),
    );
    if (registration == null) return;
    _server.register(user, registration.responseJson);
    _say('Passkey created. Next time, sign in with it.');
    setState(() {});
  });

  Future<void> _grantDrive({bool refresh = false}) => _run(() async {
    final token = await AndroidSignInKit.getAccessToken([
      GoogleScope.driveFile,
    ], forceRefresh: refresh);
    setState(() => _driveToken = token);
  });

  Future<void> _freshIdToken() => _run(() async {
    final token = await AndroidSignInKit.getIdToken();
    _say(
      token == null ? 'No ID token.' : 'ID token: ${token.substring(0, 12)}…',
    );
  });

  // Fills both fields; with "Log in now" selected, also logs in.
  Future<void> _fillSaved() => _run(() async {
    await AndroidSignInKit.getPassword(
      usernameController: _username,
      passwordController: _password,
      onPicked: _logInWhenPicked ? (_) => _logIn() : null,
    );
  });

  Future<void> _logIn() async {
    final username = _username.text.trim();
    if (username.isEmpty || _password.text.isEmpty) {
      _say('Enter a username and password.');
      return;
    }
    // Your real login call goes here. Offer to save only after it succeeds.
    _signedIn(username, Method.password);
    // Shows "Save password?" only for a new or changed password.
    final result = await AndroidSignInKit.savePassword(
      username: username,
      password: _password.text,
    );
    if (result == PasswordSaveResult.saved) _say('Password saved.');
    // Some password managers turn the login into a passkey quietly.
    final upgraded = await AndroidSignInKit.upgradeToPasskey(
      _server.registrationOptions(username),
    );
    if (upgraded != null) _server.register(username, upgraded.responseJson);
  }

  Future<void> _signOut() => _run(() async {
    // Update the screen first: clearing the sign-in state goes through
    // Google Play services and can take a moment.
    _password.clear();
    setState(() {
      _user = null;
      _method = null;
      _google = null;
    });
    await AndroidSignInKit.signOut();
  });

  Future<void> _disconnectGoogle() => _run(() async {
    await AndroidSignInKit.revokeAccess(
      scopes: [if (_driveToken != null) GoogleScope.driveFile],
    );
    setState(() {
      _user = null;
      _method = null;
      _google = null;
    });
    _say('Google account disconnected from this app.');
  });

  Future<void> _checkSetup() => _run(() async {
    final report = await AndroidSignInKit.checkSetup(
      passkeyDomain: DemoPasskeyServer.rpId,
    );
    if (report == null || !mounted) return;
    if (kDebugMode) debugPrint(report.toString());
    await showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(report.hasErrors ? 'Setup problems' : 'Setup looks good'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              for (final item in report.items)
                ListTile(
                  contentPadding: EdgeInsets.zero,
                  leading: Icon(
                    switch (item.status) {
                      SetupStatus.ok => Icons.check_circle,
                      SetupStatus.warning => Icons.info,
                      SetupStatus.error => Icons.error,
                    },
                    color: switch (item.status) {
                      SetupStatus.ok => Colors.green,
                      SetupStatus.warning => Colors.orange,
                      SetupStatus.error => Colors.red,
                    },
                  ),
                  title: Text(item.title),
                  subtitle: Text(item.detail),
                ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Android Sign-In Kit'),
        actions: [
          IconButton(
            tooltip: 'Check setup',
            onPressed: _checkSetup,
            icon: const Icon(Icons.fact_check_outlined),
          ),
        ],
        bottom: _busy
            ? const PreferredSize(
                preferredSize: Size.fromHeight(2),
                child: LinearProgressIndicator(minHeight: 2),
              )
            : null,
      ),
      body: SafeArea(
        child: ListView(
          padding: const EdgeInsets.all(24),
          children: _user != null
              ? _signedInView(context)
              : _signedOutView(context),
        ),
      ),
    );
  }

  List<Widget> _signedInView(BuildContext context) {
    final theme = Theme.of(context);
    final user = AndroidSignInKit.currentUser;
    final google = _method == Method.google;
    return [
      CircleAvatar(
        radius: 40,
        foregroundImage: google && user?.photoUrl != null
            ? NetworkImage(user!.photoUrl!)
            : null,
        child: const Icon(Icons.person, size: 40),
      ),
      const SizedBox(height: 16),
      Text(
        google ? (user?.displayName ?? _user!) : _user!,
        textAlign: TextAlign.center,
        style: theme.textTheme.headlineSmall,
      ),
      const SizedBox(height: 4),
      Text(
        switch (_method!) {
          Method.google => 'Signed in with Google',
          Method.password => 'Signed in with a password',
          Method.passkey => 'Signed in with a passkey',
        },
        textAlign: TextAlign.center,
        style: theme.textTheme.bodySmall,
      ),
      if (google) ..._googleDetails(user),
      if (_method == Method.password) ...[
        const SizedBox(height: 24),
        FilledButton.tonalIcon(
          onPressed: _createPasskey,
          icon: const Icon(Icons.fingerprint),
          label: const Text('Create a passkey'),
        ),
        const SizedBox(height: 4),
        Text(
          'Passkeys sign in with your fingerprint or screen lock, and belong '
          'to ${DemoPasskeyServer.rpId}.',
          textAlign: TextAlign.center,
          style: theme.textTheme.bodySmall,
        ),
      ],
      const SizedBox(height: 24),
      OutlinedButton(onPressed: _signOut, child: const Text('Sign out')),
      if (google) ...[
        const SizedBox(height: 8),
        TextButton(
          onPressed: _disconnectGoogle,
          child: const Text('Disconnect Google account'),
        ),
      ],
    ];
  }

  List<Widget> _googleDetails(GoogleUser? user) {
    final google = _google;
    String short(String token) => '${token.substring(0, 12)}…';
    final rows = {
      'Email': user?.email,
      'Google user ID': user?.id,
      'Given name': user?.givenName,
      'Family name': user?.familyName,
      if (google != null) ...{
        'Email verified': google.emailVerified?.toString(),
        'Workspace domain': google.hostedDomain ?? 'none (personal account)',
        'ID token': short(google.idToken),
        'Token expires': google.expiresAt?.toLocal().toString().split('.')[0],
      },
      if (_driveToken != null) 'Drive access token': short(_driveToken!),
    };
    return [
      const SizedBox(height: 16),
      Card(
        child: Column(
          children: [
            for (final MapEntry(:key, :value) in rows.entries)
              if (value != null)
                ListTile(dense: true, title: Text(key), subtitle: Text(value)),
          ],
        ),
      ),
      const SizedBox(height: 16),
      Wrap(
        spacing: 8,
        runSpacing: 8,
        alignment: WrapAlignment.center,
        children: [
          FilledButton.tonalIcon(
            onPressed: () => _grantDrive(refresh: _driveToken != null),
            icon: const Icon(Icons.add_to_drive),
            label: Text(
              _driveToken == null ? 'Allow Google Drive' : 'New Drive token',
            ),
          ),
          FilledButton.tonalIcon(
            onPressed: _freshIdToken,
            icon: const Icon(Icons.token_outlined),
            label: const Text('Fresh ID token'),
          ),
        ],
      ),
    ];
  }

  List<Widget> _signedOutView(BuildContext context) {
    final theme = Theme.of(context);
    return [
      FilledButton.icon(
        onPressed: _signIn,
        icon: const Icon(Icons.login),
        label: const Text('Sign in'),
      ),
      const SizedBox(height: 4),
      Text(
        'One sheet with your saved passwords, passkeys and Google accounts.',
        textAlign: TextAlign.center,
        style: theme.textTheme.bodySmall,
      ),
      const SizedBox(height: 16),
      GoogleSignInButton(
        expand: true,
        loading: _busy,
        onPressed: () => _signInWithGoogle(button: true),
      ),
      const SizedBox(height: 8),
      OutlinedButton.icon(
        onPressed: _signInWithGoogle,
        icon: const Icon(Icons.account_circle_outlined),
        label: const Text('Google account sheet'),
      ),
      const SizedBox(height: 8),
      OutlinedButton.icon(
        onPressed: _signInWithPasskey,
        icon: const Icon(Icons.fingerprint),
        label: const Text('Sign in with a passkey'),
      ),
      const SizedBox(height: 8),
      TextButton(
        onPressed: _lightweightSignIn,
        child: const Text('Lightweight sign-in (returning user)'),
      ),
      const Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Row(
          children: [
            Expanded(child: Divider()),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 12),
              child: Text('or'),
            ),
            Expanded(child: Divider()),
          ],
        ),
      ),
      TextField(
        controller: _username,
        keyboardType: TextInputType.emailAddress,
        // No hints on Android (they'd bring up autofill next to the
        // Credential Manager sheets); the usual ones on other platforms.
        autofillHints: AndroidSignInKit.usernameAutofillHints,
        decoration: InputDecoration(
          labelText: 'Email or username',
          border: const OutlineInputBorder(),
          prefixIcon: const Icon(Icons.alternate_email),
          // Opens the saved passwords sheet.
          suffixIcon: IconButton(
            tooltip: 'Use a saved password',
            icon: const Icon(Icons.key),
            onPressed: _fillSaved,
          ),
        ),
      ),
      const SizedBox(height: 12),
      TextField(
        controller: _password,
        obscureText: !_showPassword,
        autofillHints: AndroidSignInKit.passwordAutofillHints,
        decoration: InputDecoration(
          labelText: 'Password',
          border: const OutlineInputBorder(),
          prefixIcon: const Icon(Icons.lock_outline),
          suffixIcon: IconButton(
            tooltip: _showPassword ? 'Hide password' : 'Show password',
            icon: Icon(
              _showPassword
                  ? Icons.visibility_off_outlined
                  : Icons.visibility_outlined,
            ),
            onPressed: () => setState(() => _showPassword = !_showPassword),
          ),
        ),
      ),
      const SizedBox(height: 16),
      Text('After picking a saved password', style: theme.textTheme.labelLarge),
      const SizedBox(height: 8),
      SegmentedButton<bool>(
        segments: const [
          ButtonSegment(
            value: true,
            icon: Icon(Icons.login),
            label: Text('Log in now'),
          ),
          ButtonSegment(
            value: false,
            icon: Icon(Icons.edit_note),
            label: Text('Only fill'),
          ),
        ],
        selected: {_logInWhenPicked},
        onSelectionChanged: (value) =>
            setState(() => _logInWhenPicked = value.single),
      ),
      const SizedBox(height: 16),
      FilledButton(onPressed: () => _run(_logIn), child: const Text('Log in')),
    ];
  }
}
1
likes
150
points
267
downloads
screenshot

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Google Sign-In, passkeys and saved passwords in one sheet through Android's Credential Manager, with scopes, restore keys and a setup checker.

Repository (GitHub)
View/report issues

Topics

#google-sign-in #credential-manager #passkeys #password #authentication

Funding

Consider supporting this project:

buymeacoffee.com

License

MIT (license)

Dependencies

flutter

More

Packages that depend on android_sign_in_kit

Packages that implement android_sign_in_kit