Flutter Firebase认证插件query_stack_firebase_authentication的使用

Flutter Firebase认证插件query_stack_firebase_authentication的使用

Query Stack Firebase Authentication

A Firebase Authentication service for Query Stack。

使用

只需在您的环境中注册 AuthenticationService

@immutable
class DevelopmentEnvironment extends Environment {
  const DevelopmentEnvironment();

  [@override](/user/override)
  void registerDependencies(RegisterDependenciesDelegate when, PlatformInfo platformInfo) {
    when<AuthenticationService>(
      (get) => AuthenticationService(
        appleRedirectUrl: platformInfo.nativePlatform.when(
          onAndroid: () => "redirect url when using android", // 当使用Android时的重定向URL
          onWeb: () => "redirect url when using web",         // 当使用Web时的重定向URL
          orElse: () => null,                                 // 其他平台返回null
        ),
        appleServiceId: "apple sign in service id",           // Apple Sign In服务ID
        googleClientId: platformInfo.nativePlatform.when(
          onAndroid: () => "google client id for android",    // Android上的Google客户端ID
          oniOS: () => "google client id for ios",            // iOS上的Google客户端ID
          onWeb: () => "google client id for web",            // Web上的Google客户端ID
          orElse: () => throw UnsupportedError("${platformInfo.nativePlatform} is not supported"), // 不支持其他平台
        ),
      ),
    );

    // 注册其他依赖项
  }
}

您可以继承 AuthenticationService 并覆盖方法 fetchPesistedPrincipalpersistPrincipal,例如将已认证的用户保存到数据库中。

Principal

已认证的用户称为 Principal,其属性与Firebase Authentication用户相同:id, displayName, email, avatarURL(Firebase中的 photoURL),creationTimelastLogin

lastLogin 是一个 PrincipalLogin 类,包含 authProvider(Google或Apple)、当前设备的 id, model, device, version(如:Android 13)、platform(如:iOS、Android等)以及最后登录时间。


完整示例代码

以下是一个完整的示例,展示如何使用 query_stack_firebase_authentication 插件进行用户认证。

1. 配置环境

首先,确保您已经在Firebase控制台中配置了Google和Apple登录,并获取相应的客户端ID和服务ID。

import 'package:flutter/material.dart';
import 'package:query_stack/query_stack.dart';
import 'package:query_stack_firebase_authentication/query_stack_firebase_authentication.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: EnvironmentSetup(),
    );
  }
}

class EnvironmentSetup extends StatefulWidget {
  [@override](/user/override)
  _EnvironmentSetupState createState() => _EnvironmentSetupState();
}

class _EnvironmentSetupState extends State<EnvironmentSetup> {
  final DevelopmentEnvironment _environment = DevelopmentEnvironment();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Firebase Authentication Example")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 初始化Query Stack环境
            QueryStack.init(environment: _environment);
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (_) => HomePage()),
            );
          },
          child: Text("Initialize Environment"),
        ),
      ),
    );
  }
}

2. 创建环境配置类

@immutable
class DevelopmentEnvironment extends Environment {
  const DevelopmentEnvironment();

  [@override](/user/override)
  void registerDependencies(RegisterDependenciesDelegate when, PlatformInfo platformInfo) {
    when<AuthenticationService>(
      (get) => AuthenticationService(
        appleRedirectUrl: platformInfo.nativePlatform.when(
          onAndroid: () => "com.example.app:/oauth2redirect",
          onWeb: () => "https://example.com/oauth2callback",
          orElse: () => null,
        ),
        appleServiceId: "com.example.apple-signin-service",
        googleClientId: platformInfo.nativePlatform.when(
          onAndroid: () => "your-google-client-id-android",
          oniOS: () => "your-google-client-id-ios",
          onWeb: () => "your-google-client-id-web",
          orElse: () => throw UnsupportedError("${platformInfo.nativePlatform} is not supported"),
        ),
      ),
    );
  }
}

3. 登录页面

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home Page")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () async {
                try {
                  // 调用登录方法
                  await AuthenticationService.instance.signInWithGoogle();
                  print("User signed in successfully!");
                } catch (e) {
                  print("Error signing in: $e");
                }
              },
              child: Text("Sign in with Google"),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                try {
                  // 调用登录方法
                  await AuthenticationService.instance.signInWithApple();
                  print("User signed in successfully!");
                } catch (e) {
                  print("Error signing in: $e");
                }
              },
              child: Text("Sign in with Apple"),
            ),
          ],
        ),
      ),
    );
  }
}

4. 获取当前用户信息

class UserInfoPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("User Info")),
      body: FutureBuilder<Principal?>(
        future: AuthenticationService.instance.fetchCurrentUser(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }
          if (!snapshot.hasData || snapshot.data == null) {
            return Center(child: Text("No user logged in"));
          }
          final user = snapshot.data!;
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("User ID: ${user.id}"),
              Text("Display Name: ${user.displayName ?? "N/A"}"),
              Text("Email: ${user.email ?? "N/A"}"),
              Text("Avatar URL: ${user.avatarURL ?? "N/A"}"),
              Text("Last Login: ${user.lastLogin?.lastSignInTime?.toString() ?? "N/A"}"),
            ],
          );
        },
      ),
    );
  }
}

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

1 回复

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


query_stack_firebase_authentication 是一个用于 Flutter 的 Firebase 认证插件,它基于 query_stack 库,提供了一种简单且可扩展的方式来处理 Firebase 认证。这个插件可以帮助你轻松地集成 Firebase 认证功能到你的 Flutter 应用中。

安装

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

dependencies:
  query_stack_firebase_authentication: ^1.0.0

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

配置 Firebase

在使用 query_stack_firebase_authentication 之前,你需要确保你的 Flutter 项目已经正确配置了 Firebase。你可以按照以下步骤进行配置:

  1. 创建 Firebase 项目:在 Firebase 控制台 中创建一个新的项目。

  2. 添加 Android 应用

    • 在 Firebase 控制台中,点击“添加应用”并选择 Android。
    • 按照提示填写包名等信息。
    • 下载 google-services.json 文件并将其放在 android/app 目录下。
  3. 添加 iOS 应用

    • 在 Firebase 控制台中,点击“添加应用”并选择 iOS。
    • 按照提示填写包名等信息。
    • 下载 GoogleService-Info.plist 文件并将其放在 ios/Runner 目录下。
  4. 配置 Flutter 项目

    • android/build.gradle 文件中添加以下内容:
      dependencies {
          classpath 'com.google.gms:google-services:4.3.10'
      }
      
    • android/app/build.gradle 文件中添加以下内容:
      apply plugin: 'com.google.gms.google-services'
      
    • ios/Podfile 文件中添加以下内容:
      pod 'Firebase/Auth'
      

使用 query_stack_firebase_authentication

初始化

在你的 Flutter 应用中,首先需要初始化 query_stack_firebase_authentication

import 'package:query_stack_firebase_authentication/query_stack_firebase_authentication.dart';

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

认证服务

query_stack_firebase_authentication 提供了多种认证方式,包括电子邮件/密码、Google 登录、Facebook 登录等。

电子邮件/密码认证
final authService = FirebaseAuthenticationService();

// 注册新用户
final user = await authService.signUpWithEmailAndPassword(
  email: 'user@example.com',
  password: 'password123',
);

// 登录
final user = await authService.signInWithEmailAndPassword(
  email: 'user@example.com',
  password: 'password123',
);

// 登出
await authService.signOut();
Google 登录
final user = await authService.signInWithGoogle();
Facebook 登录
final user = await authService.signInWithFacebook();

监听认证状态

你可以使用 authService.authStateChanges 来监听用户的认证状态变化:

authService.authStateChanges.listen((user) {
  if (user != null) {
    print('User is signed in: ${user.uid}');
  } else {
    print('User is signed out');
  }
});

示例代码

以下是一个完整的示例,展示了如何使用 query_stack_firebase_authentication 进行电子邮件/密码认证:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AuthScreen(),
    );
  }
}

class AuthScreen extends StatefulWidget {
  [@override](/user/override)
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final authService = FirebaseAuthenticationService();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    authService.authStateChanges.listen((user) {
      if (user != null) {
        print('User is signed in: ${user.uid}');
      } else {
        print('User is signed out');
      }
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Auth Example'),
      ),
      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: () async {
                final user = await authService.signInWithEmailAndPassword(
                  email: emailController.text,
                  password: passwordController.text,
                );
                if (user != null) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Signed in as ${user.email}')),
                  );
                }
              },
              child: Text('Sign In'),
            ),
            ElevatedButton(
              onPressed: () async {
                final user = await authService.signUpWithEmailAndPassword(
                  email: emailController.text,
                  password: passwordController.text,
                );
                if (user != null) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Signed up as ${user.email}')),
                  );
                }
              },
              child: Text('Sign Up'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部