android_sign_in_kit

pub package License: MIT

Google Sign-In, passkeys and saved passwords for Flutter on Android, through Android's Credential Manager: one sign-in sheet for all three, Google API scopes, restore keys for new phones, a branded "Sign in with Google" button, and a setup checker that tells you what's wrong before your users do.

This is an independent package, not an official Google plugin.

The example login screen with the Sign in, Sign in with Google and passkey buttons One sheet with a saved password and Google accounts The setup check
Login screen One sheet for everything Setup check
The Google account bottom sheet Signed in, with the details from the Google ID token The saved passwords bottom sheet The Save password sheet
Google Sign-In Account details Saved passwords Save password
await AndroidSignInKit.initialize(serverClientId: webClientId); // once, in main()

// One way to sign in:
final account = await AndroidSignInKit.signInWithGoogle();
final login = await AndroidSignInKit.getPassword();
final passkey = await AndroidSignInKit.signInWithPasskey(optionsFromServer);

// Or one sheet with saved passwords, passkeys and Google accounts:
switch (await AndroidSignInKit.signIn(passkeyRequestJson: optionsFromServer)) {
  case GoogleAccount account: await server.google(account.idToken);
  case SavedPassword login: await server.login(login.username, login.password);
  case PasskeyCredential passkey: await server.passkey(passkey.responseJson);
  case null: break; // not Android
}

await AndroidSignInKit.savePassword(username: email, password: password);
await AndroidSignInKit.createPasskey(creationOptionsFromServer);
await AndroidSignInKit.signOut();

Contents

💡 Why this package

One sheet for everything Saved passwords, passkeys and Google accounts in a single sheet, so a returning user signs in with one tap whichever way they signed up.
Passkeys Create and use passkeys with your server's WebAuthn JSON, plus quiet upgrades from passwords, signals to clean up deleted passkeys, and restore keys for new phones.
The account bottom sheet The user sees the Google accounts on the phone and picks one. Nobody is signed in to an account they didn't choose.
Opens instantly initialize() gets the sheets ready in the background, so they open on tap instead of after a pause.
Everything Google sends Name, email, photo, phone, plus the claims in the ID token: Google user ID, email verified, Workspace domain, expiry.
Scopes Ask for access to Drive, Calendar or any Google API, with or without a server auth code.
Lightweight sign-in Signs a returning user in on app start with no taps, or does nothing.
Save password, only when it's new Android asks "Save password?" even for a password it already has. The package doesn't.
Remembers the user currentUser and authStateChanges survive app restarts. getIdToken() and getAccessToken() hand out fresh tokens.
Typed errors One CredentialManagerException with a code, a plain-words message, and Android's own message and type. A closed sheet (canceled) and no internet (network) are told apart, even where Google's sheet just closes.
Setup checker checkSetup() prints the package name and SHA-1 to register, and checks the Web client ID, Play services and your passkey domain's assetlinks.json.
Branded button and a test fake A "Sign in with Google" button that follows Google's guidelines, and FakeAndroidSignInKit to test your login screens anywhere.
No platform checks Every method is safe on iOS, web and desktop, so shared code needs no Platform.isAndroid.
Firebase-ready With google-services.json in the app, you don't need to pass the Web client ID at all.

🚀 Getting started

Requirements

  • Flutter 3.32 or later
  • Android minSdk 24 or later
  • Google Play services on the device (on Android 14 and later the system handles it)

Install

flutter pub add android_sign_in_kit

Passwords work right away. Google Sign-In and scopes need the setup below, and passkeys a server and a linked domain (see Passkeys).

Google Cloud setup (once)

  1. Open Google Cloud Console and pick or create a project.
  2. APIs & Services → OAuth consent screen: fill in the app name and your email. While the app is in testing, add your Google account under Test users. This app name is what Google shows on its consent screen for scopes.
  3. Credentials → Create credentials → OAuth client ID → Android: enter your app's package name (applicationId) and SHA-1.
  4. Credentials → Create credentials → OAuth client ID → Web application: just create it. Its Client ID is the serverClientId.

Get the SHA-1 of your debug key with:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android

In Credentials, check the Type column: the ID you use must say Web application. Passing an Android client ID is the most common mistake, and it fails with misconfigured.

Your app needs both clients, but your code only uses the Web client ID. The Android client is how Google recognises your app by its package name and SHA-1. The Web client ID isn't a secret; it ships inside your app.

Using Firebase?

Firebase already made both clients for you, and google-services.json contains the Web client ID. If your app applies the com.google.gms.google-services Gradle plugin (flutterfire configure sets that up), you don't need to pass serverClientId anywhere: the package reads it from the default_web_client_id resource that the plugin generates.

AndroidSignInKit.initialize(); // no client ID needed

Add your SHA-1 in Firebase console → Project settings → Your apps. To sign in to Firebase, pass the ID token on:

final account = await AndroidSignInKit.signInWithGoogle();
if (account != null) {
  await FirebaseAuth.instance.signInWithCredential(
    GoogleAuthProvider.credential(idToken: account.idToken),
  );
}

⚡ Initialize once

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AndroidSignInKit.initialize(
    serverClientId: '1234-abc.apps.googleusercontent.com', // or leave out with Firebase
  );
  runApp(const MyApp());
}

Without it, a sheet takes a moment to appear while Android looks up the accounts and passwords. initialize does that lookup in the background ahead of time, and again after each sheet, so the sheet opens as soon as the user taps. On a Galaxy A36 the Google sheet appeared in about 0.35 s instead of 0.7 to 1.1 s.

It also stores the client ID and the default options, so the other calls don't need them, and loads currentUser from the last run. Preparing needs Android 14 or later; on older versions the sheets open the usual way.

🧭 One sheet for everything

To offer just one way to sign in, call its own method. It returns its own type, so there's nothing to check:

Method Shows Returns
signInWithGoogle() Google accounts GoogleAccount
getPassword() Saved passwords SavedPassword
signInWithPasskey() Passkeys PasskeyCredential
final account = await AndroidSignInKit.signInWithGoogle();
await server.signInWithGoogle(account!.idToken);

Or use Credential Manager's main idea: one sheet with every way the user can sign in. A returning user taps their saved password, their passkey or their Google account, whichever they used before. The user decides what to pick, so signIn returns a SignInCredential, and a switch handles each kind:

try {
  final credential = await AndroidSignInKit.signIn(
    passkeyRequestJson: await server.passkeySignInOptions(), // leave out without passkeys
  );
  switch (credential) {
    case GoogleAccount account:
      await server.signInWithGoogle(account.idToken);
    case SavedPassword login:
      await server.logIn(login.username, login.password);
    case PasskeyCredential passkey:
      await server.signInWithPasskey(passkey.responseJson);
    case null:
      break; // not Android
  }
} on CredentialManagerException catch (e) {
  if (e.code == CredentialErrorCode.noCredential) showLoginForm(); // nothing saved
}

SignInCredential is a sealed class, so the compiler checks that the switch covers every case, and each case has the right type (account.idToken, login.password) without casting.

Option Default What it does
passwords true Offer saved passwords.
google true Offer Google accounts. Without internet they are left out, since they can't sign in then; passwords and passkeys still work offline.
passkeyRequestJson none Your server's WebAuthn request options. Offers the user's passkeys. See Passkeys.
onlyPreviousAccounts, autoSelect, nonce, serverClientId as in signInWithGoogle For the Google accounts.
onlyOnDevice false When the phone has nothing to offer, throw noCredential at once without showing anything, so you can show your own form straight away.

A picked password counts as known to the password manager, so a later savePassword with it doesn't ask again. A picked Google account becomes currentUser.

🔐 Google Sign-In

try {
  final account = await AndroidSignInKit.signInWithGoogle();
  if (account == null) return; // not Android
  await myServer.signIn(account.idToken); // verify the token on your server
} on CredentialManagerException catch (e) {
  if (e.code == CredentialErrorCode.canceled) return; // the user closed the sheet
  if (e.code == CredentialErrorCode.network) showMessage('No internet');
}

The sheet lists the Google accounts on the phone, with your app's name from android:label in its title.

What you get

Field From
email Credential Manager The account's email.
idToken Credential Manager A signed JWT. Send it to your server and verify it there.
displayName, givenName, familyName Credential Manager The account's name.
photoUrl Credential Manager The profile picture, if there is one.
phoneNumber Credential Manager Only for accounts made with a phone number.
id ID token (sub) Google's ID for the account. Unlike the email it never changes, so use it as the user's key.
emailVerified ID token Whether Google verified the email.
hostedDomain ID token (hd) The Google Workspace domain, or null for a personal account.
issuedAt, expiresAt ID token When the token was made and when it expires (an hour later).
nonce ID token The nonce you passed in.
claims ID token Every claim in the token, as a map.
authorization Authorization API The granted scopes, when you asked for any.

The token fields are read on the device and not verified; they're for display and convenience. Your server must verify idToken before trusting anything in it.

Options

Option Default What it does
serverClientId from initialize or google-services.json Your Web client ID.
autoSelect from initialize, else false Signs a returning user in without a tap, when exactly one account used your app before and they didn't sign out.
onlyPreviousAccounts from initialize, else false Lists only the accounts that signed in to your app before.
useButtonFlow false Shows Google's full-screen "Sign in with Google" flow instead of the sheet. Use it behind a "Sign in with Google" button. It also lets the user add an account to the phone.
hostedDomain null With useButtonFlow, only accounts of this Google Workspace domain.
nonce null Put into the ID token, so your server can check the token was made for this request. See createNonce. A call with a nonce can't use the prepared sheet.
scopes none OAuth scopes to ask for right after sign-in. See Scopes.
offlineAccess false With scopes, also get a server auth code.

Sheet or button flow?

  • Sheet (default): fast and light. Good for a login screen. If the phone has no Google account it throws noCredential.
  • Button flow: what users expect after tapping a "Sign in with Google" button. Always shows something, even with no account on the phone.

No internet? Google's sheet then shows "Signing in…" and closes by itself, which Android reports as if the user had closed it. The package checks the connection, so you get network instead of canceled. Without internet it says so at once, instead of opening a sheet that can't work.

🟦 The "Sign in with Google" button

A button that follows Google's branding guidelines: the four-color "G", Google's colors, shapes and texts, 40 px high, with Google's spacing.

GoogleSignInButton(
  onPressed: () => AndroidSignInKit.signInWithGoogle(useButtonFlow: true),
)
Option Default What it does
onPressed required Called on tap. null disables the button (38% opacity, as Google specifies).
theme dark in a dark app, else light GoogleButtonTheme.light (white, gray outline), dark (near-black) or neutral (light gray, no outline).
shape pill GoogleButtonShape.pill or rectangular.
text signInWith "Sign in with Google", "Sign up with Google", "Continue with Google" or "Sign in".
label none Your own text, such as a translation. Keep its meaning to one of Google's texts.
loading false A spinner in place of the "G", and taps are ignored.
expand false Fill the width, with the text centered.

GoogleSignInButton.icon(onPressed: ...) is the 40 × 40 button with only the "G"; screen readers read its label.

🪶 Lightweight sign-in for returning users

Like attemptLightweightAuthentication in google_sign_in. Call it when the app starts:

final account = await AndroidSignInKit.attemptLightweightSignIn();
if (account != null) {
  // A returning user: go straight to the home screen.
} else {
  // Show your login screen.
}

It only offers accounts that signed in to your app before:

Accounts that used your app before What happens
None Returns null at once. Nothing is shown.
One, and the user didn't sign out Signed in automatically, with a short "Signing in as…" banner.
One after signOut, or several A sheet with only those accounts. One tap signs in.

Closing that sheet also returns null, instead of throwing canceled. Other errors, such as network, are still thrown.

👤 The signed-in user

The package remembers the Google user, also across app restarts (after initialize), until signOut or revokeAccess:

final user = AndroidSignInKit.currentUser; // GoogleUser?, null when signed out
print(user?.email);
print(AndroidSignInKit.isSignedIn);

authStateChanges gives the current user, then every change, which is handy for picking the first screen:

StreamBuilder<GoogleUser?>(
  stream: AndroidSignInKit.authStateChanges,
  builder: (context, snapshot) =>
      snapshot.data == null ? const LoginPage() : const HomePage(),
)
GoogleUser
email The account's email.
id Google's ID for the account (sub). It never changes, unlike the email.
displayName, givenName, familyName The name.
photoUrl The profile picture.

Only the profile is stored, in the app's private storage, never a token. Any Google sign-in sets it: signInWithGoogle, attemptLightweightSignIn, signIn and the refresh in getIdToken. Passwords and passkeys are your server's accounts, so the package doesn't track those.

🎟️ Tokens: ID token, access token, nonce

ID token. getIdToken() gives a Google ID token for currentUser that is valid for at least five more minutes, for calls to your server:

final token = await AndroidSignInKit.getIdToken(); // null when signed out
await http.get(url, headers: {'Authorization': 'Bearer $token'});

ID tokens last about an hour. While the last one is fresh, it is returned as is. After that (or with forceRefresh: true), the package signs the user in again the lightweight way, which shows a brief "Signing in as…" banner (or a sheet, if several accounts used the app).

Access token. getAccessToken(scopes) gives an OAuth access token for Google APIs:

final token = await AndroidSignInKit.getAccessToken([GoogleScope.driveFile]);
final response = await http.get(driveUrl, headers: {'Authorization': 'Bearer $token'});
if (response.statusCode == 401) {
  // Revoked or expired: drop it and get a new one.
  final fresh = await AndroidSignInKit.getAccessToken(
    [GoogleScope.driveFile],
    forceRefresh: true,
  );
}

Google Play services keeps the token and renews it when it expires, so call this before each batch of API calls instead of storing the token. The first time, the user sees Google's consent screen; it throws canceled if they decline.

Nonce. createNonce() makes a random, single-use value, so a stolen ID token can't be replayed:

final nonce = AndroidSignInKit.createNonce();
final account = await AndroidSignInKit.signInWithGoogle(nonce: nonce.sha256);
await server.signIn(account!.idToken, nonce: nonce.value);
// The server checks: the token's nonce == SHA-256(nonce.value)

value is 32 random bytes (base64url) and sha256 is its SHA-256 in hex. With Firebase Auth, pass sha256 to Google and value as the raw nonce to Firebase.

🔓 Scopes: access to Google APIs

Signing in proves who the user is. To call a Google API for them (Drive, Calendar, Gmail, YouTube…), ask for its OAuth scopes. Credential Manager can't do this, so the package uses Google's Authorization API for it.

final authorization = await AndroidSignInKit.authorize(
  scopes: [GoogleScope.driveFile],
  accountEmail: account.email,
); // throws `canceled` if the user declines

final response = await http.get(
  Uri.parse('https://www.googleapis.com/drive/v3/files'),
  headers: {'Authorization': 'Bearer ${authorization.accessToken}'},
);

If the user granted the scopes before, authorize returns at once without any UI. Otherwise Google shows its consent screen with the app name from your OAuth consent screen. For just the token, getAccessToken is shorter and can refresh it.

You can also ask for scopes as part of sign-in:

final account = await AndroidSignInKit.signInWithGoogle(
  scopes: [GoogleScope.calendarReadonly],
);
final token = account?.authorization?.accessToken;

If the user signs in but declines the scopes, you still get the account, with authorization set to null; nothing is thrown.

Picking scopes

GoogleScope has constants for the common ones, so you pick them like an enum:

Area Constants
Profile email, profile, birthday, phoneNumbers, gender, addresses
Drive driveFile, driveAppData, driveReadonly, drive
Docs and Sheets documentsReadonly, documents, spreadsheetsReadonly, spreadsheets
Calendar calendarReadonly, calendarEvents, calendar
Contacts contactsReadonly, contacts
Gmail gmailSend, gmailReadonly, gmailModify
Tasks tasksReadonly, tasks
YouTube youtubeReadonly, youtube

Google has hundreds more, so it isn't a closed Dart enum: any other scope works by its URL, for example GoogleScope('https://www.googleapis.com/auth/fitness.activity.read'). See Google's list of scopes.

GoogleAuthorization
accessToken Short-lived token for calling Google APIs from the app.
grantedScopes What the user granted. Can be less than you asked for; check with hasScope(GoogleScope.driveFile).
serverAuthCode Only with offlineAccess: true: a one-time code your server exchanges for a refresh token, to call Google APIs while the user is away.
email The account that granted access.
authorize option
scopes The OAuth scopes.
accountEmail Which account. Without it, Google asks.
hostedDomain Only accounts of this Google Workspace domain.
offlineAccess Also return serverAuthCode. Needs the Web client ID.
forceRefreshToken Ask Google for a new refresh token even if your server got one before.

Sensitive scopes (Gmail, full Drive…) show an "unverified app" warning until Google verifies your app. drive.file and the profile scopes don't.

🔑 Saving and picking passwords

Save after login

Call savePassword after your login or sign-up call succeeds:

await myServer.logIn(email, password);

final result = await AndroidSignInKit.savePassword(
  username: email,
  password: password,
);
result What happened
PasswordSaveResult.saved The "Save password?" sheet showed and the user saved it (or updated a changed password).
PasswordSaveResult.unchanged The password is already saved, so no sheet was shown.
PasswordSaveResult.declined The user tapped "Cancel" or closed the sheet. Saving is up to the user, so this is a result, not a canceled error.
PasswordSaveResult.unsupported Not on Android. See iOS and other platforms.

Why unchanged matters. Android shows "Save password?" every time an app asks, even for a password that's already saved, and apps can't check what's saved without showing a sheet. So the package remembers which logins are already in the password manager: ones saved with savePassword and ones picked with getPassword. For those it doesn't ask again, even after the app restarts. A changed password isn't known, so the sheet shows and the user can update it.

It stores only a keyed hash of each login (HMAC-SHA256 with a key that stays in the Android Keystore), never the password. If getPassword finds nothing saved any more, it forgets them all and asks again next time.

Only save a password that worked. Saving one before the server accepts it leaves a wrong password in the user's password manager.

When no password manager on the phone can save passwords, savePassword throws noProvider. AndroidSignInKit.openPasswordSettings() opens the system screen where the user turns one on (Android 14 and later; it returns false on older versions).

Pick a saved one

await AndroidSignInKit.getPassword(
  usernameController: emailController,
  passwordController: passwordController,
);

The picked login is put into your fields. getPassword also returns it as a SavedPassword, so you can leave the controllers out and use saved.username and saved.password yourself. If the user closes the sheet, it throws canceled and leaves the fields as they were.

The sheet shows the passwords saved for your app. If there are none, it throws CredentialManagerException with noCredential, so you can hide the button or just do nothing. With onlyOnDevice: true, that happens without any UI at all.

SavedPassword.toString() leaves the password out, so printing it won't put the password in your logs.

After picking: log in now, or only fill

When the user picks a saved login, your app decides what happens next, with onPicked. The example app lets you try both.

Log in now. Picking a saved login usually means "log me in", so skip the extra tap. Pass your login function as onPicked; it runs right after the fields are filled:

Future<void> useSavedPassword() => AndroidSignInKit.getPassword(
  usernameController: emailController,
  passwordController: passwordController,
  onPicked: (_) => logIn(), // your normal login, straight away
);

Only fill. Leave onPicked out. The fields are filled and the user checks them and taps your Log in button:

Future<void> useSavedPassword() => AndroidSignInKit.getPassword(
  usernameController: emailController,
  passwordController: passwordController,
);

To let users choose, pass onPicked only when they want it, for example from a setting: onPicked: logInWhenPicked ? (_) => logIn() : null.

If the user closes the sheet, nothing is filled and onPicked isn't called. onPicked gets the SavedPassword too, in case you'd rather log in with it than read the fields.

Either way, your logIn() can end with savePassword as usual. For a login that was picked from the sheet it returns PasswordSaveResult.unchanged without showing anything, so there's no need to tell the two cases apart:

Future<void> logIn() async {
  await myServer.logIn(emailController.text, passwordController.text);
  await AndroidSignInKit.savePassword(
    username: emailController.text,
    password: passwordController.text,
  ); // asks only for a new or changed password
}

A good place for the button is a key icon inside the field:

TextField(
  controller: passwordController,
  obscureText: true,
  decoration: InputDecoration(
    labelText: 'Password',
    suffixIcon: IconButton(
      tooltip: 'Use a saved password',
      icon: const Icon(Icons.key),
      onPressed: useSavedPassword,
    ),
  ),
)

🔏 Passkeys

A passkey replaces a password with the phone's screen lock or fingerprint. It's made for one website (your relying party, such as example.com) and synced by the user's password manager. Nothing secret ever reaches your server, so there's nothing to steal or phish.

What you need

  1. A server with a WebAuthn library. The phone signs; your server creates the challenge and checks the answer. Use a proven library, such as SimpleWebAuthn (Node.js), py_webauthn (Python), java-webauthn-server or webauthn4j (Java and Kotlin). The package passes the WebAuthn JSON between your server and Android as is, so any of them works.
  2. Your app linked to the domain. Serve this at https://example.com/.well-known/assetlinks.json, with your package name and the SHA-256 of each signing key (debug, release, Play app signing):
[{
  "relation": ["delegate_permission/common.get_login_creds"],
  "target": {
    "namespace": "android_app",
    "package_name": "com.example.app",
    "sha256_cert_fingerprints": ["AB:CD:..."]
  }
}]

checkSetup(passkeyDomain: 'example.com') prints your SHA-256 and checks the file. Without the link, passkey calls fail with misconfigured.

Create a passkey

After the user signed in (or as part of sign-up), ask your server for creation options and pass them on:

final options = await server.passkeyCreationOptions(); // PublicKeyCredentialCreationOptions JSON
final registration = await AndroidSignInKit.createPasskey(options);
await server.savePasskey(registration!.responseJson);
Throws When
canceled The user said no.
passkeyExists The password manager already has one of the passkeys the server listed in excludeCredentials.
misconfigured The domain's assetlinks.json doesn't list this app.
noProvider No password manager on the phone stores passkeys.

Sign in with a passkey

final options = await server.passkeySignInOptions(); // PublicKeyCredentialRequestOptions JSON
final passkey = await AndroidSignInKit.signInWithPasskey(options);
await server.verifyPasskey(passkey!.responseJson);

passkey.credentialId and passkey.userId (the userHandle) are read from the JSON for convenience; your server must verify the whole response. To offer passkeys together with passwords and Google accounts, pass the same options to signIn instead. With onlyOnDevice: true, it throws noCredential without any UI when the phone has no passkey.

Upgrade password users quietly

Right after a successful password login, some password managers can create a passkey without asking ("conditional create"):

final upgraded = await AndroidSignInKit.upgradeToPasskey(await server.passkeyCreationOptions());
if (upgraded != null) await server.savePasskey(upgraded.responseJson);

It never shows a prompt and never throws. null means no passkey was made, which is normal where the password manager or Android version doesn't support it.

Keep the password manager up to date

When passkeys change on your server, tell the user's password manager, so it stops offering ones that no longer work. These are hints: they return whether the password manager got them, never throw, and not every password manager supports them.

Call When
signalUnknownPasskey(rpId:, credentialId:) A sign-in used a passkey your server doesn't know (deleted, or from an old account).
signalAcceptedPasskeys(rpId:, userId:, credentialIds:) After a sign-in, or after the user deleted a passkey in your app: the full list your server accepts.
signalUserDetails(rpId:, userId:, name:, displayName:) The user changed their email or name.

♻️ Restore keys: signed in on a new phone

A restore key is a passkey-like key that comes back with the app's data when the user moves to a new phone or reinstalls the app. Use it to sign them back in without any screen:

// After every sign-in (no UI):
final key = await AndroidSignInKit.createRestoreKey(await server.passkeyCreationOptions());
await server.saveRestoreKey(key!.responseJson);

// On the first launch:
final restored = await AndroidSignInKit.getRestoreKey(await server.passkeySignInOptions());
if (restored != null) await server.signInWithRestoreKey(restored.responseJson);

// When the user signs out:
await AndroidSignInKit.clearRestoreKey();

Your server treats it like a passkey. getRestoreKey returns null when there is none, without showing anything. With cloudBackup: true (the default), the key travels with the user's Google backup to a new phone, so it needs the user's backup turned on; with false it only survives a reinstall on the same phone. It needs Google Play services.

🪪 Digital IDs

getDigitalCredential(requestJson) asks for an ID card, driver's license or age proof from a wallet on the phone, such as Google Wallet, for an identity or age check without photos of documents. requestJson is an OpenID4VP request from your verifier service; send the returned JSON back to it.

final response = await AndroidSignInKit.getDigitalCredential(await verifier.request());
await verifier.check(response!);

This uses Credential Manager's digital credentials API, which Android marks as experimental, and it only finds IDs the user added to a supporting wallet. It throws canceled when the user declines and noCredential when no wallet has a matching ID.

✍️ Autofill hints

With this package, leave autofill hints off your login fields on Android. Flutter only turns autofill on for a field when you set autofillHints.

With hints, Android autofill (the older Google Password Manager integration) runs next to Credential Manager. It shows its own "Use your saved password?" sheet as soon as a field is focused, which can appear before or on top of the Credential Manager sheet, and it shows saved logins above the keyboard. Users then see two different-looking sheets for the same thing.

On iOS, web and desktop it's the other way round: autofill hints are how the keychain or the browser fills and saves passwords. So the package has getters that do the right thing on each platform, and you never need a Platform.isAndroid check:

Getter On Android Elsewhere
AndroidSignInKit.usernameAutofillHints null (autofill off) [AutofillHints.username]
AndroidSignInKit.passwordAutofillHints null [AutofillHints.password]
AndroidSignInKit.emailAutofillHints null [AutofillHints.email]
AndroidSignInKit.newUsernameAutofillHints null [AutofillHints.newUsername]
AndroidSignInKit.newPasswordAutofillHints null [AutofillHints.newPassword]

Use the first two (or emailAutofillHints for an email field) on the login screen, and the new... ones on a sign-up or change-password screen, where iOS can then suggest a strong password:

AutofillGroup(
  child: Column(
    children: [
      TextField(
        controller: emailController,
        autofillHints: AndroidSignInKit.usernameAutofillHints,
      ),
      TextField(
        controller: passwordController,
        obscureText: true,
        autofillHints: AndroidSignInKit.passwordAutofillHints,
      ),
    ],
  ),
)

Hints that have nothing to do with logins, such as AutofillHints.name, telephoneNumber, postalAddress or oneTimeCode, don't compete with Credential Manager. Set those directly as usual.

If you keep login hints on Android anyway, the package still prevents the worst part: savePassword ends the autofill session first, so the user gets one "Save password?" prompt, not two.

🚪 Signing out and disconnecting

await AndroidSignInKit.signOut();

Call it when the user signs out of your app. It clears currentUser and tells Credential Manager to forget the last sign-in, so autoSelect and lightweight sign-in won't sign the same account in again without a tap. It doesn't remove saved passwords, passkeys, granted scopes or Google accounts from the phone.

Clearing that state goes through Google Play services and can take a second. Nothing on screen depends on it, so update your UI first and don't make the user wait:

setState(() => user = null); // back to the login screen at once
await AndroidSignInKit.signOut();

Disconnecting the Google account

revokeAccess goes further: it disconnects your app from the user's Google account, as if they removed it under Third-party apps & services in their Google account. The granted scopes are taken back, the next sign-in asks for consent again, and the user is signed out.

await AndroidSignInKit.revokeAccess(scopes: [GoogleScope.driveFile]);

Call it when the user deletes their account in your app; Google recommends that apps using Google Sign-In offer this. Pass the scopes you were granted, if any.

⚠️ Errors

Every failure throws CredentialManagerException, including a closed sheet (canceled), so you can tell "the user changed their mind" from "something broke":

try {
  await AndroidSignInKit.signInWithGoogle();
} on CredentialManagerException catch (e) {
  print(e.code);            // CredentialErrorCode.misconfigured
  print(e.message);         // what it means, in plain words
  print(e.platformMessage); // Android's message: "[28444] Developer console is not set up correctly."
  print(e.platformType);    // Android's error type, or the Play services status name
  print(e.statusCode);      // Play services status code, for authorize
}
code When
canceled The user closed the sheet, or said no on the consent screen or the passkey prompt. Usually nothing to show. (savePassword returns declined instead, and attemptLightweightSignIn and getRestoreKey return null.)
noCredential Nothing to show: no saved passwords, or no (returning) Google account on the phone.
misconfigured Google rejected the app: wrong Web client ID, or no Android client with this package name and SHA-1. Also when there's no Web client ID at all, and for passkeys when the domain's assetlinks.json doesn't list the app.
providerUnavailable Google Play services or the credential provider is missing, disabled or out of date.
unsupported The device doesn't support Credential Manager.
noProvider No password manager on the phone can save passwords or passkeys. openPasswordSettings() lets the user turn one on.
interrupted The request was interrupted, for example by the app going to the background. Try again.
network No internet connection, or Google couldn't be reached. The package checks the connection, because Google's sheet closes by itself without internet and Android reports that as a cancel.
passkeyExists createPasskey: the password manager already has a passkey for this account.
invalidToken The Google ID token couldn't be read.
unexpectedCredential Android returned a different kind of credential than asked for.
noActivity The app wasn't in the foreground.
busy Another authorize call is still waiting for the user.
unknown Anything else. Check platformMessage.

upgradeToPasskey and the signal… calls are the exceptions: they never throw, and return null or false instead.

message is meant for logs. For users, show your own text based on code.

"Developer console is not set up correctly"

This comes back as misconfigured. Check that:

  • you use the Web client ID, not the Android one,
  • the Android client's package name matches your applicationId,
  • its SHA-1 matches the key the app is signed with (debug, release and Play App Signing keys are all different; add each one as its own Android client),
  • both clients are in the same Google Cloud project,
  • while the app is in testing, your account is a test user.

Changes in Google Cloud Console can take a few minutes to apply. checkSetup() shows the package name and SHA-1 of the running build, so you can compare them.

🩺 Check your setup

Most sign-in problems are setup problems: an Android client with the wrong SHA-1, the Android client ID passed where the Web one belongs, or a passkey domain that doesn't list the app. checkSetup looks at the running build and tells you:

if (kDebugMode) print(await AndroidSignInKit.checkSetup(passkeyDomain: 'example.com'));
android_sign_in_kit setup (has problems):
✓ Package name: com.example.app
✓ Signing certificate SHA-1: 3B:1F:...:9A
    → Google Cloud Console → Credentials needs an Android OAuth client with this package name and SHA-1, ...
! Build: debug build, signed with the debug key
    → Release builds use your upload key, and apps from Google Play the app signing key ...
✓ Web client ID: 123456789012…ogleusercontent.com (from google-services.json)
✓ Google Play services: available
✓ Android: API 36
✗ Passkey domain: https://example.com/.well-known/assetlinks.json doesn't list this build's SHA-256
    → Add AB:CD:... to sha256_cert_fingerprints.
✓ Signing certificate SHA-256: AB:CD:...
It checks How
Package name and SHA-1 Read from the running app, ready to paste into Google Cloud Console.
Debug build Reminds you that release and Play builds are signed with other keys.
Web client ID Found the same way as initialize (argument or google-services.json), and checked to be a client ID.
Google Play services Installed and usable.
Android version Passkeys need Android 9 or later.
Passkey domain With passkeyDomain: downloads assetlinks.json and checks the relation, the package and the SHA-256, and gives the exact statement to add.

It returns a SetupReport (items, hasErrors, packageName, sha1, sha256) for your own debug screen. It can't see your Google Cloud project, so a wrong SHA-1 there still only shows at sign-in, as misconfigured; compare the printed one with the console. The Web client ID is shortened in the report.

🧪 Testing your app

FakeAndroidSignInKit answers the package's calls in tests, on any machine, without Android or a Google account:

import 'package:android_sign_in_kit/testing.dart';

late FakeAndroidSignInKit fake;
setUp(() => fake = FakeAndroidSignInKit()..install());
tearDown(() => fake.uninstall());

testWidgets('Google sign-in shows the home page', (tester) async {
  await tester.pumpWidget(const MyApp());
  await tester.tap(find.byType(GoogleSignInButton));
  await tester.pumpAndSettle();
  expect(find.text('Hello, Test User'), findsOneWidget);
});

testWidgets('a closed sheet keeps the login page', (tester) async {
  fake.nextError = CredentialErrorCode.canceled;
  // ...
});
Fake
googleEmail, googleName The Google account every sheet "picks". Its ID token is a real-looking, unsigned JWT.
passwords The saved passwords. getPassword returns the first; savePassword adds to them and returns unchanged for a known one.
pick What signIn returns: FakeSignInPick.google, password or passkey.
passkeyResponseJson, restoreKeyResponseJson, digitalCredentialJson What the passkey, restore key and digital ID calls return.
nextError The next sheet fails with this code, such as canceled or network.
tokenLifetime How long its ID tokens last, to test getIdToken refreshing.
calls, methods What your app asked for, with the arguments.
storedUser The stored user, to test what happens after a restart.

While installed, AndroidSignInKit.isSupported is true on every platform.

🗝️ Password managers other than Google's

On Android 14 and later, Credential Manager works with every password manager the user turned on in Settings → Passwords, passkeys and accounts, such as Samsung Pass, 1Password, Bitwarden or Dashlane, as long as that app supports Credential Manager:

  • getPassword and signIn list the saved logins and passkeys from all of them in one sheet.
  • savePassword and createPasskey save to the user's preferred one, and the sheet's "Save another way" lets them pick another.

On Android 13 and lower, Credential Manager goes through Google Play services, so only Google Password Manager is used.

📦 Release builds

The package ships the R8 rules Credential Manager needs, so minified release builds work without changes.

For apps on Google Play, add the SHA-1 of the app signing key as another Android client, and for passkeys its SHA-256 to your assetlinks.json. You'll find both in Play Console under Test and release → App integrity.

🍎 iOS and other platforms

Credential Manager only exists on Android, but you don't need Platform.isAndroid checks: every method can be called from shared code. On other platforms nothing is shown and nothing is thrown:

Method On iOS, web and desktop
initialize, signOut, revokeAccess, clearRestoreKey Do nothing.
signIn, signInWithGoogle, attemptLightweightSignIn, authorize, getPassword, createPasskey, upgradeToPasskey, signInWithPasskey, createRestoreKey, getRestoreKey, getDigitalCredential, getIdToken, getAccessToken, checkSetup Return null.
openPasswordSettings, the signal… calls Return false.
currentUser null.
savePassword Returns PasswordSaveResult.unsupported, after letting the iOS keychain or the browser offer to save (see below).

So the same login code runs everywhere. Use isSupported only to hide buttons that would do nothing, such as "Use a saved password":

if (AndroidSignInKit.isSupported)
  IconButton(icon: const Icon(Icons.key), onPressed: useSavedPassword),

On iOS, saving and filling passwords works through autofill hints and the keychain. Use the package's autofill hint getters on your fields: they're off on Android and on everywhere else. With them, the savePassword you already call after login also makes iOS offer to save the password to the keychain.

Example

The example app is a login screen with:

  • the one sheet for passwords, passkeys and Google accounts;
  • the "Sign in with Google" button, the account sheet and lightweight sign-in, the signed-in user (kept across restarts), a fresh ID token, Drive access with a refreshable token, and disconnecting the account;
  • password save and pick (log in directly or just fill the fields), and a quiet passkey upgrade after a password login;
  • creating and using passkeys. Its "server" runs inside the app and only checks the challenge, so it shows the flow, not a secure server. It forgets the passkeys when the app restarts, which also shows signalUnknownPasskey at work;
  • the setup check, from the button in the app bar.

Passwords work right away. Google Sign-In and passkeys need your own Google Cloud clients and passkey domain, because they trust only apps signed with a key they know. The example's README walks you through it, then:

flutter run --dart-define=WEB_CLIENT_ID=1234-abc.apps.googleusercontent.com

☕ Support

If this package saves you time, you can support its maintenance with a coffee:

Buy Me a Coffee

Or scan the code:

QR code for buymeacoffee.com/parthbhensdadiya

License

MIT

Libraries

android_sign_in_kit
Google Sign-In, saved passwords and passkeys through Android's Credential Manager.
testing
A fake Credential Manager for testing apps that use android_sign_in_kit: FakeAndroidSignInKit().install() in setUp.