Future<void>main()async{WidgetsFlutterBinding.ensureInitialized();awaitFirebase.initializeApp();// Ideal time to initializeawaitFirebaseAuth.instance.useAuthEmulator('localhost',9099);//...}
FirebaseAuth.instance.authStateChanges().listen((User?user){if(user==null){print('User is currently signed out!');}else{print('User is signed in!');}});
// Disable persistence on web platforms. Must be called on initialization:finalauth=FirebaseAuth.instanceFor(app:Firebase.app(),persistence:Persistence.NONE);// To change it after initialization, use `setPersistence()`:awaitauth.setPersistence(Persistence.LOCAL);
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-25 (世界標準時間)。"],[],[],null,["# Get Started with Firebase Authentication on Flutter\n\n\u003cbr /\u003e\n\nConnect your app to Firebase\n----------------------------\n\n[Install and initialize the Firebase SDKs for Flutter](/docs/flutter/setup) if you haven't already done\nso.\n\nAdd Firebase Authentication to your app\n---------------------------------------\n\n1. From the root of your Flutter project, run the following command to install\n the plugin:\n\n flutter pub add firebase_auth\n\n2. Once complete, rebuild your Flutter application:\n\n flutter run\n\n3. Import the plugin in your Dart code:\n\n import 'package:firebase_auth/firebase_auth.dart';\n\nTo use an authentication provider, you need to enable it in the [Firebase console](https://console.firebase.google.com/).\nGo to the Sign-in Method page in the Firebase Authentication section to enable\nEmail/Password sign-in and any other identity providers you want for your app.\n\n(Optional) Prototype and test with Firebase Local Emulator Suite\n----------------------------------------------------------------\n\nBefore talking about how your app authenticates users, let's introduce a set of\ntools you can use to prototype and test Authentication functionality:\nFirebase Local Emulator Suite. If you're deciding among authentication techniques\nand providers, trying out different data models with public and private data\nusing Authentication and Firebase Security Rules, or prototyping sign-in UI designs, being able to\nwork locally without deploying live services can be a great idea.\n\nAn Authentication emulator is part of the Local Emulator Suite, which\nenables your app to interact with emulated database content and config, as\nwell as optionally your emulated project resources (functions, other databases,\nand security rules).\n\nUsing the Authentication emulator involves just a few steps:\n\n1. Adding a line of code to your app's test config to connect to the emulator.\n\n2. From the root of your local project directory, running `firebase emulators:start`.\n\n3. Using the Local Emulator Suite UI for interactive prototyping, or the\n Authentication emulator REST API for non-interactive testing.\n\n4. Call `useAuthEmulator()` to specify the emulator address and port:\n\n Future\u003cvoid\u003e main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n\n // Ideal time to initialize\n await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);\n //...\n }\n\nA detailed guide is available at [Connect your app to the Authentication emulator](/docs/emulator-suite/connect_auth).\nFor more information, see the [Local Emulator Suite introduction](/docs/emulator-suite).\n\nNow let's continue with how to authenticate users.\n\nCheck current auth state\n------------------------\n\nFirebase Auth provides many methods and utilities for enabling you to integrate\nsecure authentication into your new or existing Flutter application. In many\ncases, you will need to know about the authentication *state* of your user,\nsuch as whether they're logged in or logged out.\n\nFirebase Auth enables you to subscribe in realtime to this state via a\n[`Stream`](https://api.flutter.dev/flutter/dart-async/Stream-class.html).\nOnce called, the stream provides an immediate event of the user's current\nauthentication state, and then provides subsequent events whenever\nthe authentication state changes.\n\nThere are three methods for listening to authentication state changes:\n\n### `authStateChanges()`\n\nTo subscribe to these changes, call the `authStateChanges()` method on your\n`FirebaseAuth` instance: \n\n FirebaseAuth.instance\n .authStateChanges()\n .listen((User? user) {\n if (user == null) {\n print('User is currently signed out!');\n } else {\n print('User is signed in!');\n }\n });\n\nEvents are fired when the following occurs:\n\n- Right after the listener has been registered.\n- When a user is signed in.\n- When the current user is signed out.\n\n### `idTokenChanges()`\n\nTo subscribe to these changes, call the `idTokenChanges()` method on your\n`FirebaseAuth` instance: \n\n FirebaseAuth.instance\n .idTokenChanges()\n .listen((User? user) {\n if (user == null) {\n print('User is currently signed out!');\n } else {\n print('User is signed in!');\n }\n });\n\nEvents are fired when the following occurs:\n\n- Right after the listener has been registered.\n- When a user is signed in.\n- When the current user is signed out.\n- When there is a change in the current user's token.\n\n\u003cbr /\u003e\n\n| If you set custom claims using the Firebase Admin SDK, you will only see this event fire when the following occurs:\n|\n| \u003cbr /\u003e\n|\n| - A user signs in or re-authenticates after the custom claims are modified. The ID token issued as a result will contain the latest claims.\n| - An existing user session gets its ID token refreshed after an older token expires.\n| - An ID token is force refreshed by calling `FirebaseAuth.instance.currentUser.getIdTokenResult(true)`.\n|\n| For further details, see [Propagating custom claims to the client](/docs/auth/admin/custom-claims#propagate_custom_claims_to_the_client)\n\n\u003cbr /\u003e\n\n### `userChanges()`\n\nTo subscribe to these changes, call the `userChanges()` method on your\n`FirebaseAuth` instance: \n\n FirebaseAuth.instance\n .userChanges()\n .listen((User? user) {\n if (user == null) {\n print('User is currently signed out!');\n } else {\n print('User is signed in!');\n }\n });\n\nEvents are fired when the following occurs:\n\n- Right after the listener has been registered.\n- When a user is signed in.\n- When the current user is signed out.\n- When there is a change in the current user's token.\n- When the following methods provided by `FirebaseAuth.instance.currentUser` are called:\n - `reload()`\n - `unlink()`\n - `updateEmail()`\n - `updatePassword()`\n - `updatePhoneNumber()`\n - `updateProfile()`\n\n\u003cbr /\u003e\n\n| `idTokenChanges()`, `userChanges()` \\& `authStateChanges()` will not fire if you update the `User` profile with the Firebase Admin SDK. You will have to force a reload using `FirebaseAuth.instance.currentUser.reload()` to retrieve the latest `User` profile.\n|\n| \u003cbr /\u003e\n|\n| `idTokenChanges()`, `userChanges()` \\& `authStateChanges()` will also not fire\n| if you disable or delete the `User` with the Firebase Admin SDK or the Firebase\n| console. You will have to force a reload using\n| `FirebaseAuth.instance.currentUser.reload()`, which will cause a `user-disabled`\n| or `user-not-found` exception that you can catch and handle in your app code.\n\n\u003cbr /\u003e\n\nPersisting authentication state\n-------------------------------\n\nThe Firebase SDKs for all platforms provide out of the box support for ensuring\nthat your user's authentication state is persisted across app restarts or page\nreloads.\n\nOn native platforms such as Android \\& iOS, this behavior is not configurable\nand the user's authentication state will be persisted on device between app\nrestarts. The user can clear the apps cached data using the device settings,\nwhich will wipe any existing state being stored.\n\nOn web platforms, the user's authentication state is stored in\n[IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API).\nYou can change the persistence to store data in the [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)\nusing `Persistence.LOCAL`.\nIf required, you can change this default behavior to only persist\nauthentication state for the current session, or not at all. To configure these\nsettings, call the following method `FirebaseAuth.instanceFor(app: Firebase.app(), persistence: Persistence.LOCAL);`.\nYou can still update the persistence for each Auth instance using `setPersistence(Persistence.NONE)`. \n\n // Disable persistence on web platforms. Must be called on initialization:\n final auth = FirebaseAuth.instanceFor(app: Firebase.app(), persistence: Persistence.NONE);\n // To change it after initialization, use `setPersistence()`:\n await auth.setPersistence(Persistence.LOCAL);\n\nNext Steps\n----------\n\nExplore the guides on signing in and signing up users with the supported\nidentity and authentication services."]]