Flutter身份验证插件fireauth的使用

Flutter身份验证插件fireauth的使用

Fireauth

Fireauth 是一个旨在简化 Flutter Firebase 身份验证并加快应用开发速度的 Flutter 包。它提供了一种直观的方式来访问 Firebase 身份验证套件的一部分,并减少了你在这方面的开发时间。 适用于 Flutter 原生和 Flutter Web!

安装

在你的 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  fireauth: ^0.9.0

然后运行以下命令来获取包:

$ flutter packages get

接着添加导入语句:

import 'package:fireauth/fireauth.dart';

项目 Firebase 设置

使用我的 FireSetup 工具

正确设置 Firebase 以与 FireAuth 提供的所有身份验证方法一起工作有时会很困难且繁琐!因此,我编写了一个 Python 脚本来为你完成大部分工作!它还包含详细的文档说明,使整个过程非常顺利。这比官方文档更好!

🔴 如果你不使用 FireSetup,则可能会由于手动设置错误而出现问题。

平台支持

  • Android(完全支持)
  • Web(完全支持)
  • iOS(完全支持)
  • macOS(依赖项不支持)
  • Windows(依赖项不支持)
  • Linux(依赖项不支持)

当前支持的身份验证方法

  • 匿名
  • 邮箱和密码注册和登录
  • 手机号
  • Google
  • Twitter
  • GitHub
  • Microsoft
  • Facebook
  • Yahoo
  • Apple(未测试)
  • 无密码(实现待定)

⚠️ 大多数这些身份验证方法需要额外设置!所有详细信息都可以在 FireSetup README 中找到。


使用

☑️ fireauth 导出并公开了 firebase_core、firebase_auth 和 provider 包!因此,你无需单独导入它们!这确保了你的项目不会因多个导入而变得混乱!你可以在这里找到依赖版本:pubspec.yaml

步骤 1:初始化 Firebase(main.dart)

void main() async {
  // 这将根据需要初始化 Firebase(重要)
  await initializeFirebase();  // 这个方法来自 fireauth 包
  runApp(YourApp());
}

步骤 2:用 FireAuth 包裹你的 Material App

// 允许从任何地方访问身份验证方法
return FireAuth(
  child: MaterialApp(
    home: MyAppHome(),
  ),
);

步骤 3:使用 AuthManager

// 这基本上像一个网关,如果你已登录,它将显示目标页面
// 否则,它将显示登录页面(它还会记住认证状态!)
return AuthManager(
  loginFragment: LoginPage(),
  destinationFragment: HomePage(),
);

使用 AuthController

AuthController 是一个 Dart 类,其中包含几个静态方法,提供了有用的函数!

使用 Google 登录

🟡 GoogleSignIn 需要额外设置

AuthController.signInWithGoogle(
  context,
  onError: (String e) {},
  onSignInSuccessful: (User u) {},
);

匿名登录

AuthController.signInAnonymously(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

使用手机号登录

🟡 PhoneSignIn 需要额外设置

AuthController.signInWithPhoneNumber(
  context,
  phoneNumber: phoneNumberController.value.text,
  onError: (e) {},
  onInvalidVerificationCode: () {},
  onSignInSuccessful: (User u) {},
);

使用邮箱和密码注册和登录

AuthController.registerWithEmailAndPassword(
  context,
  email: "example@email.com",
  password: "abc123",
  onError: (String e) {},
  onRegisterSuccessful: (User u) {},
);

使用邮箱和密码登录

AuthController.signInWithEmailAndPassword(
  context,
  email: "example@email.com",
  password: "abc123",
  onError: (String e) {},
  onIncorrectCredentials: () {},
  onSignInSuccessful: (User u) {},
);

使用 Facebook 登录

🟡 FacebookSignIn 需要额外设置

AuthController.signInWithFacebook(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

使用 OAuth2 登录

🟡 OAuthSignIn 需要额外设置

// Twitter OAuth 登录
AuthController.signInWithTwiter(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

// GitHub OAuth 登录
AuthController.signInWithGithub(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

// Microsoft OAuth 登录
AuthController.signInWithMicrosoft(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

// Yahoo OAuth 登录
AuthController.signInWithYahoo(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

// Apple OAuth 登录(iOS 上的原生登录)
AuthController.signInWithApple(
  context,
  onSignInSuccessful: (User u) {},
  onError: (String e) {},
);

登出

AuthController.logout(context);

获取当前用户

AuthController.getCurrentUser(
  context,
  // 可选参数,如果不提供,它只会返回一个 Firebase 用户
  customMapping: (user) => {
    'name': user.displayName,
    'email': user.email,
  },
);

社交登录按钮

如果你只需要一个可以启用特定社交登录的现成按钮,那么这些就是你需要的小部件!

import 'package:fireauth/fireauth.dart';

// 社交按钮
TwitterSocialButton(),
GithubSocialButton(),
MicrosoftSocialButton(),
GoogleSocialButton(),
FacebookSocialButton(),
// 这个按钮使用新的 Facebook 设计语言
NewFacebookSocialButton(),
YahooSocialButton(),
AnonymousSocialButton(),
AppleSocialButton(),

// 微型社交按钮
MiniTwitterSocialButton(),
MiniGithubSocialButton(),
MiniMicrosoftSocialButton(),
MiniGoogleSocialButton(),
MiniFacebookSocialButton(),
// 这个按钮使用新的 Facebook 设计语言
MiniNewFacebookSocialButton(),
MiniAnonymousSocialButton(),
MiniYahooSocialButton(),
AppleSocialButton(),

/* 每个按钮都接受一个 SocialButtonConfiguration!例如:
GoogleSocialButton(
  config: SocialButtonConfiguration(
    foregroundColor: Colors.black,
    backgroundColor: Colors.white,
    onSignInSuccessful: (user) {
      print("GoogleSignIn 成功!!! UID: ${user.uid}");
    },
    onError: (e) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text("GoogleOAuth 错误发生"),
          content: Text(e),
        ),
      );
    },
  ),
),
更多信息可以在 SocialButtonConfiguration 类的文档字符串中找到
*/

未来计划

  • 将 FireAuth 移动到 Sound Null Safety
  • 声明生产就绪状态

FireAuth 更改日志

实时示例(FlutterWeb)


以下是完整的示例代码,展示了如何使用 FireAuth 进行身份验证:

import 'package:fireauth/SocialButtons/util.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// 导入 FireAuth
import 'package:fireauth/fireauth.dart';

void main() async {
  // 这将根据需要初始化 Firebase(重要)
  await initializeFirebase();
  runApp(FireAuthExampleApp());
}

class FireAuthExampleApp extends StatelessWidget {
  const FireAuthExampleApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 总是添加这个在 Material App 之上,它会暴露一个内部的 Provider
    // 可以从任何地方访问 AuthInformation
    return FireAuth(
      child: MaterialApp(
        home: AppOrigin(),
      ),
    );
  }
}

class AppOrigin extends StatelessWidget {
  const AppOrigin({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 这基本上像一个网关,如果你已登录,它将显示目的地
    // 如果你未登录,它将显示登录页面(记住认证状态!)
    return AuthManager(
      loginFragment: LoginPage(),
      destinationFragment: HomePage(),
      // 其他参数用于设置登录期间的等待屏幕,可选
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  [@override](/user/override)
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController regEmailController = TextEditingController();
  TextEditingController regPassController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController passController = TextEditingController();
  TextEditingController phoneNumberController = TextEditingController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Color(0xFF333333),
        constraints: BoxConstraints.expand(),
        padding: EdgeInsets.symmetric(
            vertical: kIsWeb ? 10 : 20, horizontal: kIsWeb ? 10 : 20),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 30),
              Text(
                "FireAuth 示例",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 40,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20),
              Text(
                "社交登录",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
              ),
              SizedBox(height: 20),
              // 全尺寸社交按钮
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  TwitterSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "TwitterSignIn 成功!!! UID: ${user!.uid}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("TwitterOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  GithubSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "GithubSignIn 成功!!! UID: ${user!.uid}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("GithubOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  MicrosoftSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "MicrosoftSignIn 成功!!! UID: ${user!.uid}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("MicrosoftOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  GoogleSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "GoogleSignIn 成功!!! UID: ${user!.uid}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("GoogleOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  FacebookSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "FacebookSignIn 成功!!! 名称: ${user!.displayName}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("FacebookOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  NewFacebookSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "FacebookSignIn 成功!!! 名称: ${user!.displayName}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("FacebookOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  YahooSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "YahooSignIn 成功!!! 名称: ${user!.displayName}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("YahooOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                  AppleSocialButton(
                    config: SocialButtonConfiguration(
                      onSignInSuccessful: (user) {
                        print(
                          "AppleSignIn 成功!!! 名称: ${user!.displayName}",
                        );
                      },
                      onError: (e) {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text("AppleOAuth 错误发生"),
                            content: Text(e),
                          ),
                        );
                      },
                    ),
                  ),
                ].spaceBetweenColumnElements(8),
              ),
              SizedBox(height: 20),
              // 微型登录按钮
              Container(
                width: 260,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        MiniTwitterSocialButton(),
                        MiniGithubSocialButton(),
                        MiniMicrosoftSocialButton(),
                        MiniGoogleSocialButton(),
                        MiniFacebookSocialButton(),
                      ].spaceBetweenRowElements(10),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        MiniNewFacebookSocialButton(),
                        MiniAnonymousSocialButton(),
                        MiniYahooSocialButton(),
                        MiniAppleSocialButton(),
                      ].spaceBetweenRowElements(10),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20),
              // FireAuth 提供的匿名登录按钮,如果需要,可以自定义颜色
              Text(
                "匿名认证",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 15),
              AnonymousSocialButton(
                config: SocialButtonConfiguration(
                  onSignInSuccessful: (user) {
                    print(
                      "匿名登录成功!!! UID: ${user!.uid}",
                    );
                  },
                ),
              ),
              SizedBox(height: 30),
              Text(
                "手机认证",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20),
              Container(
                padding: EdgeInsets.all(10),
                color: Colors.white,
                width: 400,
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: phoneNumberController,
                        decoration:
                            InputDecoration(hintText: '+CC 电话号码'),
                      ),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    ElevatedButton.icon(
                      onPressed: () {
                        // 这是如何发起一个手机号登录
                        AuthController.signInWithPhoneNumber(
                          context,
                          phoneNumber: phoneNumberController.value.text,
                          onError: (e) {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text("PhoneAuth 错误发生"),
                                content: Text(e),
                              ),
                            );
                          },
                          onInvalidVerificationCode: () {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text("无效验证码"),
                                content: Text(
                                  "你提供的 SMS 代码或 OTP 是错误的,请重试",
                                ),
                              ),
                            );
                          },
                          closeVerificationPopupAfterSubmit: false,
                          // 成功登录的回调
                          onSignInSuccessful: (user) {
                            print(
                              "PhoneSignIn 成功!!! 电话: ${user!.phoneNumber}",
                            );
                          },
                        );
                      },
                      icon: Icon(Icons.phone),
                      label: Container(
                        height: 50,
                        child: Center(
                          child: Text(
                            '手机登录',
                            style: TextStyle(fontSize: 18),
                          ),
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        primary: Colors.green[500],
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 30),
              Text(
                "使用邮箱和密码注册",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(
                height: 15,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                margin: EdgeInsets.symmetric(horizontal: kIsWeb ? 100 : 0),
                child: Column(
                  children: [
                    TextField(
                      controller: regEmailController,
                      decoration: InputDecoration(hintText: '注册邮箱'),
                    ),
                    SizedBox(height: 10),
                    TextField(
                      controller: regPassController,
                      decoration:
                          InputDecoration(hintText: '注册密码'),
                    ),
                    SizedBox(height: 10),
                    ElevatedButton(
                      onPressed: () {
                        // 这是如何使用邮箱和密码进行注册
                        AuthController.registerWithEmailAndPassword(
                          context,
                          email: regEmailController.value.text,
                          password: regPassController.value.text,
                          onError: (String e) {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text("错误发生"),
                                content: Text(e),
                              ),
                            );
                          },
                          onRegisterSuccessful: (user) {
                            print(
                                "成功注册邮箱: ${user!.email}");
                          },
                        );
                      },
                      child: Text("注册并登录"),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 30),
              Text(
                "使用邮箱和密码登录",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(
                height: 15,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                margin: EdgeInsets.symmetric(horizontal: kIsWeb ? 100 : 0),
                child: Column(
                  children: [
                    TextField(
                      controller: emailController,
                      decoration: InputDecoration(hintText: '登录邮箱'),
                    ),
                    SizedBox(height: 10),
                    TextField(
                      controller: passController,
                      decoration: InputDecoration(hintText: '登录密码'),
                    ),
                    SizedBox(height: 10),
                    ElevatedButton(
                      onPressed: () {
                        // 这是如何使用邮箱和密码进行登录
                        AuthController.signInWithEmailAndPassword(
                          context,
                          email: emailController.value.text,
                          password: passController.value.text,
                          onIncorrectCredentials: () {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text("错误的凭据"),
                                content: Text(
                                  "邮箱或密码错误,或者这种组合不存在。请再试一次。",
                                ),
                              ),
                            );
                          },
                          onError: (String e) {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text("错误发生"),
                                content: Text(e),
                              ),
                            );
                          },
                          // 成功登录的回调
                          onSignInSuccessful: (user) {
                            print(
                              "Email 登录成功!!! 邮箱: ${user!.email}",
                            );
                          },
                        );
                      },
                      child: Text("登录"),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20),
              // 使用 AuthController.logout(context) 从任何地方注销
              GenericSocialButton(
                name: '注销',
                initiator: (context) => AuthController.logout(
                  context,
                ),
                foregroundColor: Colors.white,
                backgroundColor: Colors.red[700],
                customString: '注销',
              ),
              SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("首页"),
        actions: [
          // 注销
          IconButton(
            icon: Icon(Icons.logout),
            onPressed: () {
              AuthController.logout(
                context,
                onLogout: () {
                  print("注销成功");
                },
              );
            },
          ),
          IconButton(
            icon: Icon(Icons.person),
            onPressed: () async {
              print(
                AuthController.getCurrentUser(
                  context,
                  // 使用 customMapping 参数从 Firebase 用户创建自己的用户表示
                  // customMapping: (user) => {
                  //   'email': user.email,
                  //   'name': user.displayName,
                  // },
                ),
              );
            },
          )
        ],
      ),
    );
  }
}

extension ListSpacing on List<Widget> {
  List<Widget> spaceBetweenRowElements(double x) {
    List<Widget> y = [];
    this.forEach((e) {
      y.add(e);
      y.add(SizedBox(width: x));
    });
    return y.sublist(0, y.length - 1);
  }

  List<Widget> spaceBetweenColumnElements(double x) {
    List<Widget> y = [];
    this.forEach((e) {
      y.add(e);
      y.add(SizedBox(height: x));
    });
    return y.sublist(0, y.length - 1);
  }
}

更多关于Flutter身份验证插件fireauth的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter身份验证插件fireauth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中使用Firebase Authentication(通常称为fireauth)进行身份验证是一个常见的需求。Firebase Authentication 提供了多种身份验证方法,如电子邮件/密码、电话号码、Google 登录、Facebook 登录等。以下是如何在 Flutter 中使用 Firebase Authentication 的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 Firebase 和 Firebase Authentication 的依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: latest_version
  firebase_auth: latest_version

然后运行 flutter pub get 来安装依赖。

2. 初始化 Firebase

main.dart 文件中初始化 Firebase:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Auth',
      home: AuthScreen(),
    );
  }
}

3. 设置 Firebase Authentication

AuthScreen 中,你可以使用 FirebaseAuth 实例来进行身份验证操作。

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

class AuthScreen extends StatefulWidget {
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  Future<void> _signInWithEmailAndPassword() async {
    try {
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: _emailController.text,
        password: _passwordController.text,
      );
      print("User signed in: ${userCredential.user!.email}");
    } on FirebaseAuthException catch (e) {
      print("Failed to sign in: ${e.message}");
    }
  }

  Future<void> _signUpWithEmailAndPassword() async {
    try {
      UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
        email: _emailController.text,
        password: _passwordController.text,
      );
      print("User registered: ${userCredential.user!.email}");
    } on FirebaseAuthException catch (e) {
      print("Failed to register: ${e.message}");
    }
  }

  Future<void> _signOut() async {
    await _auth.signOut();
    print("User signed out");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Auth'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'Email'),
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _signInWithEmailAndPassword,
              child: Text('Sign In'),
            ),
            ElevatedButton(
              onPressed: _signUpWithEmailAndPassword,
              child: Text('Sign Up'),
            ),
            ElevatedButton(
              onPressed: _signOut,
              child: Text('Sign Out'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 处理用户状态

你可以使用 FirebaseAuthauthStateChangesuserChanges 流来监听用户的登录状态:

@override
void initState() {
  super.initState();
  _auth.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });
}

5. 其他身份验证方法

Firebase Authentication 还支持其他身份验证方法,如 Google 登录、Facebook 登录、匿名登录等。你可以根据需要添加这些功能。

例如,Google 登录需要额外的依赖和配置:

dependencies:
  google_sign_in: latest_version

然后按照 Google 登录的文档进行配置和实现。

6. 处理错误

在使用 Firebase Authentication 时,务必处理可能发生的错误,如无效的电子邮件、密码错误、网络问题等。你可以使用 FirebaseAuthException 来捕获和处理这些错误。

7. 注销和删除用户

你可以使用 signOut 方法来注销用户:

await _auth.signOut();

如果你想删除用户,可以使用 delete 方法:

await user.delete();
回到顶部