You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Flutter Web应用集成Firebase预构建Auth UI?

Hey there! As someone who’s struggled with the same Firebase Auth UI confusion when starting out with Flutter Web, let me walk you through this step by step—no overly technical jargon, just actionable steps.

First off: Yes, Firebase’s prebuilt Auth UI works perfectly with Flutter Web! The official docs are great but can feel overwhelming for newbies, so let’s break it down into simple parts.

1. Set Up Firebase & Add Required Scripts

First, make sure you’ve created a Firebase project and added a Web app to it (you can do this in the Firebase Console). Grab your Firebase config snippet, then head to your Flutter project’s web/index.html file and add these scripts inside the <head> tag:

<!-- Firebase Core SDK -->
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"></script>
<!-- Firebase Auth SDK -->
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-auth.js"></script>
<!-- Firebase UI Auth SDK + CSS -->
<script src="https://www.gstatic.com/firebasejs/ui/6.0.2/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.2/firebase-ui-auth.css" />

Next, add your Firebase config and initialize Firebase right after those scripts:

<script>
  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
  };
  firebase.initializeApp(firebaseConfig);
</script>
2. Build a Flutter Widget to Host Firebase UI

Since Firebase UI is a JavaScript library, we’ll use Flutter’s web capabilities to render it in a widget. Create a new StatefulWidget:

import 'dart:js' as js;
import 'package:flutter/material.dart';

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

  @override
  State<FirebaseAuthUI> createState() => _FirebaseAuthUIState();
}

class _FirebaseAuthUIState extends State<FirebaseAuthUI> {
  @override
  void initState() {
    super.initState();
    // Call our custom JS function to initialize Firebase UI
    js.context.callMethod('initFirebaseUI');
  }

  @override
  Widget build(BuildContext context) {
    // This container will be replaced by the Firebase Auth UI
    return Container(
      key: const Key('firebase-auth-container'),
      width: double.infinity,
      height: 500,
      // Optional: Add a loading spinner while UI loads
      child: const Center(child: CircularProgressIndicator()),
    );
  }
}

Now go back to web/index.html and add the initFirebaseUI JavaScript function (put it right after your Firebase config):

<script>
  function initFirebaseUI() {
    const authUI = new firebaseui.auth.AuthUI(firebase.auth());
    
    // Configure which sign-in methods you want to enable
    const uiConfig = {
      signInSuccessUrl: '/', // Route to navigate after successful login
      signInOptions: [
        // Add all the providers you want here (not just Google!)
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.EmailAuthProvider.PROVIDER_ID,
        firebase.auth.PhoneAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        // Add Twitter/GitHub/etc. if you enable them in Firebase Console
      ],
      // Optional: Disable account selection if you don't need it
      credentialHelper: firebaseui.auth.CredentialHelper.NONE,
    };

    // Render the UI into the Flutter container (match the ID!)
    authUI.start('#firebase-auth-container', uiConfig);
  }
</script>
3. Listen for Auth State in Flutter

Even though we’re using the JS UI, you can still use Flutter’s firebase_auth package to track the user’s authentication state. First, add the dependencies to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.15.0
  firebase_auth: ^4.10.0

Initialize Firebase in your main.dart:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

Then listen for auth changes to update your UI:

// In your main app or home widget
@override
void initState() {
  super.initState();
  FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user != null) {
      // User is logged in—navigate to your home screen
      Navigator.pushReplacementNamed(context, '/home');
    } else {
      // User is logged out—show the FirebaseAuthUI widget
      Navigator.pushReplacementNamed(context, '/login');
    }
  });
}
4. Enable Sign-In Methods in Firebase Console

Don’t forget to head to your Firebase Console > Authentication > Sign-in method and enable all the providers you added in the signInOptions (Google, Email/Password, Phone, etc.). Each provider has its own setup steps (like adding a Facebook App ID or configuring phone verification templates).

Quick Tips for Newbies

  • Always test with flutter run -d chrome (Firebase UI won’t work in mobile emulators for Web projects)
  • If you run into CORS errors, add your local development URL (like http://localhost:5000) to Firebase Console > Authentication > Settings > Authorized domains
  • Make sure your Firebase SDK versions in index.html are compatible with the firebase_auth package version you’re using (check the package docs for matching versions)

内容的提问来源于stack exchange,提问作者Alberto Pereda Rojas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:42:27