Firebase Phone Authentication in Flutter: A Practical Guide
Phone-number sign-in is one of the few auth flows where the platform does half the work for you: the OS auto-fills the SMS code, and Firebase verifies the number before you ever trust a user. In Flutter the whole flow fits into a handful of async calls, but the failure modes (no reCAPTCHA, wrong test numbers, throttled sends) are where most implementations stall.
This guide walks through a working Firebase phone auth setup on Flutter: wiring the plugin, sending and verifying the OTP, handling the common error codes, and testing without burning real SMS quota. It assumes you already have a Firebase project linked to your app and focus on the parts that actually break in production.
Prerequisites and plugin setup
Add firebase_core and firebase_auth to pubspec.yaml, then run flutterfire configure so the google-services.json and GoogleService-Info.plist land in the right places. On Android, enable the SafetyNet/Play Integrity API in the Firebase console or you will get a silent reCAPTCHA fallback. On iOS, upload your APNs key and enable push notifications in Xcode; without it, silent verification cannot deliver the code and the SDK falls back to the browser flow, which looks broken to users.
Call Firebase.initializeApp() once in main before runApp, and make sure the minSdkVersion is at least 21 on Android (23 if you enable Play Integrity). If you use flavors or multiple Firebase projects, pass the correct options object explicitly rather than relying on the default config file.
- Android: enable Play Integrity in Firebase console
- iOS: upload APNs auth key, enable Push Notifications capability
- Android minSdk 21+, iOS 13+ for current plugin versions
- Set SHA-1 and SHA-256 fingerprints in the Firebase project
Sending the verification code
The send call is verifyPhoneNumber. Pass the E.164 number (leading plus, country code, no spaces), a timeout between 30 and 60 seconds, and separate callbacks for codeSent, verificationCompleted, verificationFailed, and codeAutoRetrievalTimeout. Keep a reference to the verificationId from codeSent; you will need it to verify the SMS code.
Auto-retrieval gives you a PhoneAuthCredential through verificationCompleted without the user typing anything. Treat that as a real sign-in: call signInWithCredential immediately. One caveat that bites people — the callback can fire on a platform channel thread, so hop to the UI isolate before touching state. Also, on Android the SDK sometimes completes auto-retrieval seconds after you have already shown the OTP field, so guard against double sign-in.
- Use E.164 format: +14155550123
- Store verificationId in state or a ViewModel
- Guard verificationCompleted against double sign-in
- Set timeout 30-60 seconds
| Error code | Typical cause | What to do |
|---|---|---|
| invalid-phone-number | Missing + or country code | Normalize to E.164 before sending |
| invalid-verification-code | User typed the wrong 6 digits | Let them retry, count attempts |
| session-expired | verificationId older than ~15 min | Restart the send flow |
| too-many-requests | Repeat sends to one number | Disable resend for 60 seconds |
| quota-exceeded | Project-wide SMS limit | Check console usage, request increase |
| app-not-authorized | Missing SHA fingerprint | Add SHA-1 and SHA-256, re-download config |
| missing-client-identifier | No Play Integrity or reCAPTCHA | Enable the API, rebuild the app |
Verifying the OTP and signing in
When the user submits the code, build a PhoneAuthCredential with PhoneAuthProvider.credential(verificationId: id, smsCode: code) and pass it to signInWithCredential. Wrap it in try/catch and map FirebaseAuthException codes to messages: invalid-verification-code means a typo, session-expired means the verificationId is stale (usually over 10-15 minutes old), and credential-already-in-use means the number is already linked in some configurations.
After a successful sign-in, FirebaseAuth.instance.currentUser gives you the user. If this is a first sign-in, create a profile record; the phone number arrives as user.phoneNumber. Persist nothing yourself — the SDK restores the session, and authStateChanges() is the stream your app should listen to for navigation. Keep the sign-in state logic in a StatefulWidget or a state holder rather than rebuilding auth calls on every build, as covered in StatelessWidget vs StatefulWidget: Which One Should You Pick?.
Errors, throttling, and abuse
Firebase enforces per-number and per-project send limits. In testing you may hit too-many-requests after roughly 5-10 sends to the same number in a short window; production quotas are higher but not unlimited. Handle it by disabling the resend button for 60 seconds and surfacing a clear message instead of a raw exception string.
Also handle quota-exceeded, network-request-failed, and app-not-authorized. The last one almost always means your SHA fingerprint is missing or you changed your debug keystore. For abuse, enable App Check with Play Integrity on Android and App Attest on iOS; without it, your project is a free SMS sender for anyone with your API key.
- Back off 60 seconds before resend
- Map error codes to human messages
- Enable App Check to stop SMS abuse
- Verify SHA-1/SHA-256 when app-not-authorized appears
Testing without spending SMS
In the Firebase console under Authentication > Sign-in method > Phone, add test phone numbers with fixed codes, for example +1 555 555 0123 with code 123456. These bypass real SMS, work offline from the carrier, and do not count against quota. They are the fastest way to run the full flow in CI or on a fresh emulator.
Test numbers do not exercise auto-retrieval or the reCAPTCHA fallback, so run at least a few real-number tests on a physical device before release. Emulators without Play Services cannot do silent verification at all; use a Google Play image, not an AOSP one. If the flow depends on state that survives rotation, make sure it does — see Handling Configuration Changes in Kotlin Without Losing State for the native side of that problem.
Where it fits in your auth stack
Phone auth is strongest as a second factor or as a low-friction first login for markets where SMS is universal. It is weaker as the only factor because numbers get recycled by carriers; a user who loses their number can lose the account. Offer email or a recovery path alongside it, and require re-verification before sensitive actions like changing the linked number.
Keep the flow in one place: a service class that exposes sendCode, verifyCode, and a stream of auth state. Screens should be thin. Before you ship, walk the failure paths the same way you would a database change — methodically, with a checklist, as in Room Database Migration Checklist Before You Ship.
Key points
- Use E.164 numbers and store the verificationId from codeSent
- Treat verificationCompleted as a real sign-in and guard against double calls
- Add test phone numbers in the console to develop without SMS quota
- Enable App Check and set SHA fingerprints before release
Flutter Screen Widget and Cost Estimator
Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.
Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.