Flutter身份验证插件vyuh_feature_auth的使用

Flutter身份验证插件vyuh_feature_auth的使用


Vyuh Logo

Vyuh Framework

构建模块化、可扩展、CMS驱动的Flutter应用

文档 | 网站

Vyuh Feature Auth 🔐 #

vyuh_feature_auth

Vyuh应用程序的身份验证功能,提供灵活且可定制的身份验证流程。此包包括多种身份验证方法,如电子邮件/密码、手机OTP和OAuth,并通过Sanity.io CMS进行内容驱动的UI组件。

功能 ✨ #

  • 多种身份验证方法 🔑: 支持电子邮件/密码、手机OTP和OAuth认证
  • 内容驱动表单 📝: 使用Sanity.io CMS自定义的身份验证表单
  • 灵活布局 🎨: 多种布局选项以适应不同的呈现风格
  • 动作集成 🔄: 内置动作用于身份验证流程,如登录、注册和密码重置
  • 错误处理 ⚠️: 全面的错误处理和用户反馈

安装 📦 #

将以下依赖添加到你的`pubspec.yaml`文件中:
dependencies:
  vyuh_feature_auth: any

使用 💡 #

功能注册 #

在你的Vyuh应用程序设置中注册身份验证功能:
import 'package:vyuh_core/vyuh_core.dart' as vyuh;
import 'package:vyuh_feature_auth/vyuh_feature_auth.dart' as auth;

void main() {
  vyuh.runApp(
    initialLocation: '/',
    plugins: _getPlugins(),
    features: () => [
      auth.feature,
      // ... 其他功能
    ],
  );
}

内容示例 🎯 #

电子邮件/密码表单 📧

创建并渲染一个电子邮件/密码表单:
import 'package:vyuh_core/vyuh_core.dart' as vyuh;
import 'package:vyuh_feature_auth/vyuh_feature_auth.dart' as auth;
import 'package:vyuh_extension_content/vyuh_extension_content.dart';
import 'package:vyuh_feature_system/vyuh_feature_system.dart' as system;

// 创建并渲染一个电子邮件/密码表单
final form = auth.EmailPasswordForm(
  actionType: auth.AuthActionType.signIn,
  showPasswordVisibilityToggle: true,
  action: Action(
    title: '登录',
    configurations: [
      system.NavigationAction(
        navigationType: system.NavigationType.replace,
        linkType: system.LinkType.url,
        url: '/dashboard',
      ),
    ],
  ),
  forgotPasswordAction: Action(
    title: '忘记密码',
    configurations: [
      system.NavigationAction(
        navigationType: system.NavigationType.push,
        linkType: system.LinkType.url,
        url: '/auth/forgot-password',
      ),
    ],
  ),
);

// 在小部件中渲染
class SignInPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: vyuh.content.buildContent(context, form),
    );
  }
}

手机OTP表单 📱

创建并渲染一个手机OTP表单:
// 创建并渲染一个手机OTP表单
final form = auth.PhoneOtpForm(
  action: Action(
    title: '验证OTP',
    configurations: [
      AuthConfiguration(
        schemaType: 'auth.verifyOtp',
        redirectTo: '/dashboard',
      ),
      system.NavigationAction(
        navigationType: system.NavigationType.replace,
        linkType: system.LinkType.url,
        url: '/dashboard',
      ),
    ],
  ),
);

// 在小部件中渲染
vyuh.content.buildContent(context, form);

OAuth 登录 🔗

创建并渲染OAuth登录选项:
// 创建并渲染OAuth登录选项
final oauth = auth.OAuthSignIn(
  providers: [
    Action(
      title: '使用Google登录',
      configurations: [
        AuthConfiguration(
          schemaType: 'auth.oauth',
          provider: 'google',
        ),
        system.NavigationAction(
          navigationType: system.NavigationType.replace,
          linkType: system.LinkType.url,
          url: '/dashboard',
        ),
      ],
    ),
    Action(
      title: '使用GitHub登录',
      configurations: [
        AuthConfiguration(
          schemaType: 'auth.oauth',
          provider: 'github',
        ),
        system.NavigationAction(
          navigationType: system.NavigationType.replace,
          linkType: system.LinkType.url,
          url: '/dashboard',
        ),
      ],
    ),
  ],
);

// 在小部件中渲染
vyuh.content.buildContent(context, oauth);

提示动作文本 💭

创建并渲染带有动作的提示文本:
// 创建并渲染带有动作的提示文本
final hint = auth.HintActionText(
  text: '还没有账户?',
  action: Action(
    title: '注册',
    configurations: [
      system.NavigationAction(
        navigationType: system.NavigationType.push,
        linkType: system.LinkType.url,
        url: '/auth/signup',
      ),
    ],
  ),
  actionText: '注册',
);

// 在小部件中渲染
vyuh.content.buildContent(context, hint);

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

1 回复

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


vyuh_feature_auth 是一个用于身份验证的 Flutter 插件,通常用于处理用户登录、注册、会话管理等功能。以下是使用 vyuh_feature_auth 插件的基本步骤和示例代码。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 vyuh_feature_auth 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  vyuh_feature_auth: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在你的 Flutter 应用启动时,初始化 vyuh_feature_auth 插件。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化身份验证插件
  await VyuhAuth.initialize(
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    projectId: 'YOUR_PROJECT_ID',
  );

  runApp(MyApp());
}

3. 用户登录

使用 VyuhAuth 提供的 signInWithEmailAndPassword 方法进行用户登录。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

Future<void> loginUser(String email, String password) async {
  try {
    UserCredential userCredential = await VyuhAuth.instance.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
    print('User logged in: ${userCredential.user?.email}');
  } on AuthException catch (e) {
    print('Login failed: ${e.message}');
  }
}

4. 用户注册

使用 VyuhAuth 提供的 createUserWithEmailAndPassword 方法进行用户注册。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

Future<void> registerUser(String email, String password) async {
  try {
    UserCredential userCredential = await VyuhAuth.instance.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );
    print('User registered: ${userCredential.user?.email}');
  } on AuthException catch (e) {
    print('Registration failed: ${e.message}');
  }
}

5. 检查用户登录状态

你可以使用 VyuhAuth 提供的 currentUser 属性来检查当前用户是否已登录。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

void checkUserLoginStatus() {
  User? user = VyuhAuth.instance.currentUser;
  if (user != null) {
    print('User is logged in: ${user.email}');
  } else {
    print('No user is logged in');
  }
}

6. 用户登出

使用 VyuhAuth 提供的 signOut 方法进行用户登出。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

Future<void> logoutUser() async {
  await VyuhAuth.instance.signOut();
  print('User logged out');
}

7. 监听身份验证状态变化

你可以使用 VyuhAuth 提供的 authStateChanges 流来监听用户身份验证状态的变化。

import 'package:vyuh_feature_auth/vyuh_feature_auth.dart';

void listenToAuthState() {
  VyuhAuth.instance.authStateChanges().listen((User? user) {
    if (user != null) {
      print('User is logged in: ${user.email}');
    } else {
      print('No user is logged in');
    }
  });
}

8. 完整示例

以下是一个完整的示例,展示了如何使用 vyuh_feature_auth 插件进行用户登录、注册和登出。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  await VyuhAuth.initialize(
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    projectId: 'YOUR_PROJECT_ID',
  );

  runApp(AuthApp());
}

class AuthApp 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 _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    listenToAuthState();
  }

  void listenToAuthState() {
    VyuhAuth.instance.authStateChanges().listen((User? user) {
      if (user != null) {
        print('User is logged in: ${user.email}');
      } else {
        print('No user is logged in');
      }
    });
  }

  Future<void> _login() async {
    await loginUser(_emailController.text, _passwordController.text);
  }

  Future<void> _register() async {
    await registerUser(_emailController.text, _passwordController.text);
  }

  Future<void> _logout() async {
    await logoutUser();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('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: _login,
              child: Text('Login'),
            ),
            ElevatedButton(
              onPressed: _register,
              child: Text('Register'),
            ),
            ElevatedButton(
              onPressed: _logout,
              child: Text('Logout'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部