Flutter认证管理插件agconnect_auth的使用

Flutter认证管理插件agconnect_auth的使用

简介

大多数应用程序需要识别和验证用户以定制每个用户的体验。然而,从头开始构建这样的系统是一个复杂的过程。认证服务可以快速为您的应用程序构建一个安全可靠的用户认证系统。您只需要在应用程序中访问认证服务的功能,而无需关心云上的设施和实现。

了解更多

安装插件

将依赖项添加到Flutter项目的pubspec.yaml文件中:

dependencies:
  agconnect_auth: ^1.9.0+300

在终端页面运行以下命令或在Android Studio中点击Pub get来添加依赖项:

flutter pub get

有关详细信息,请参阅 Flutter入门指南

开发指南

使用方法

使用说明

参考文档

参考文档

许可证

认证插件遵循以下许可证:Apache License, version 2.0


完整示例代码

/*
 * Copyright 2020-2023. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'dart:async';
import 'dart:io';

import 'package:agconnect_auth/agconnect_auth.dart';
import 'package:agconnect_auth_example/custom_button.dart';
import 'package:agconnect_auth_example/pages/page_huawei.dart';
import 'package:agconnect_auth_example/pages/page_huawei_game.dart';
import 'package:flutter/material.dart';

import 'pages/page_anonymous.dart';
import 'pages/page_email.dart';
import 'pages/page_google.dart';
import 'pages/page_google_game.dart';
import 'pages/page_phone.dart';
import 'pages/page_self_build.dart';
import 'pages/page_user.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(home: HomePage());
  }
}

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

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

class HomePageState extends State<HomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
    addTokenListener();
  }

  void _showDialog(BuildContext context, String content) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            key: const Key("dialog"),
            title: const Text("结果"),
            content: Text(content),
            actions: [
              TextButton(
                child: const Text("关闭"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  Future<void> addTokenListener() async {
    if (!mounted) return;

    AGCAuth.instance.tokenChanges().listen((TokenSnapshot event) {
      debugPrint("事件: $event , ${event.state}, ${event.token}");
    }, onError: (Object error) {
      debugPrint('错误: $error');
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AGC Auth 示例'),
        ),
        body: Center(
            child: ListView(
          children: [
            CustomButton('匿名登录', () async {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const PageAnonymousAuth()));
            }),
            CustomButton('手机号登录', () async {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const PagePhoneAuth()));
            }),
            CustomButton('邮箱登录', () async {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const PageEmailAuth()));
            }),
            CustomButton('自建登录', () async {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const PageSelfBuildAuth()));
            }),
            CustomButton('用户信息', () async {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => const PageUser()));
            }),
            CustomButton('华为登录', () async {
              if (Platform.isAndroid) {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => const PageHuaweiAuth()));
              } else if (Platform.isIOS) {
                _showDialog(context,
                    "此认证模式仅适用于Android。");
              }
            }),
            CustomButton('华为游戏登录', () async {
              if (Platform.isAndroid) {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const PageHuaweiGameAuth()));
              } else if (Platform.isIOS) {
                _showDialog(context,
                    "此认证模式仅适用于Android。");
              }
            }),
            CustomButton('Google登录', () async {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const PageGoogleAuth()));
            }),
            CustomButton('Google游戏登录', () async {
              if (Platform.isAndroid) {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const PageGoogleGameAuth()));
              } else if (Platform.isIOS) {
                _showDialog(context,
                    "此认证模式仅适用于Android。");
              }
            }),
            CustomButton('支持的认证列表', () async {
              _showDialog(
                  context,
                  (await AGCAuth.instance.getSupportedAuthList())!.map((i) => i.toString()).join(","));
            }),
            CustomButton('Twitter登录', () async {
              _showDialog(
                  context,
                  "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
            }),
            CustomButton('Facebook登录', () async {
              _showDialog(
                  context,
                  "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
            }),
            CustomButton('Apple登录', () async {
              if (Platform.isAndroid) {
                _showDialog(context,
                    "此认证模式仅适用于iOS。");
              } else if (Platform.isIOS) {
                _showDialog(
                    context,
                    "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
              }
            }),
            CustomButton('微信登录', () async {
              _showDialog(
                  context,
                  "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
            }),
            CustomButton('微博登录', () async {
              _showDialog(
                  context,
                  "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
            }),
            CustomButton('QQ登录', () async {
              _showDialog(
                  context,
                  "请集成相关的第三方插件并检索参数以启用此功能,您可以阅读readme以获取详细信息。");
            }),
          ],
        )),
      ),
    );
  }
}

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

1 回复

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


agconnect_auth 是华为提供的用于在 Flutter 应用中实现用户认证管理的插件。它支持多种认证方式,包括手机号码认证、邮箱认证、第三方认证(如华为账号、微信、QQ、Facebook等)。以下是 agconnect_auth 的基本使用步骤。

1. 安装插件

首先,在 pubspec.yaml 文件中添加 agconnect_auth 依赖:

dependencies:
  flutter:
    sdk: flutter
  agconnect_auth: ^latest_version

然后运行 flutter pub get 来安装插件。

2. 配置 Huawei AGConnect

在使用 agconnect_auth 之前,你需要在华为开发者平台上创建项目并启用相关服务。

  1. 登录 华为开发者联盟
  2. 创建一个新项目或使用现有项目。
  3. 在项目中启用 Auth Service
  4. 下载 agconnect-services.json 文件,并将其放置在 Flutter 项目的 android/app 目录下。

3. 初始化 AGConnect

在 Flutter 应用启动时,需要初始化 AGConnect。通常在 main.dart 中进行初始化:

import 'package:agconnect_auth/agconnect_auth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 AGConnect
  await AGConnectAuth.instance.initialize();
  
  runApp(MyApp());
}

4. 实现用户认证

手机号码认证

import 'package:agconnect_auth/agconnect_auth.dart';

Future<void> signInWithPhone() async {
  try {
    // 发送验证码
    await AGConnectAuth.instance.requestVerifyCode(
      "+8613812345678", // 手机号码
      VerifyCodeSettings(
        action: VerifyCodeAction.registerLogin,
        sendInterval: 30,
        locale: Locale.CHINA
      )
    );

    // 用户输入验证码后,进行验证
    AuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(
      "+8613812345678",
      "123456" // 用户输入的验证码
    );

    // 登录
    User user = await AGConnectAuth.instance.signIn(credential);
    print("User signed in: ${user.uid}");
  } catch (e) {
    print("Error: $e");
  }
}

邮箱认证

Future<void> signInWithEmail() async {
  try {
    // 发送验证码
    await AGConnectAuth.instance.requestVerifyCode(
      "user@example.com", // 邮箱地址
      VerifyCodeSettings(
        action: VerifyCodeAction.registerLogin,
        sendInterval: 30,
        locale: Locale.ENGLISH
      )
    );

    // 用户输入验证码后,进行验证
    AuthCredential credential = EmailAuthProvider.credentialWithVerifyCode(
      "user@example.com",
      "123456" // 用户输入的验证码
    );

    // 登录
    User user = await AGConnectAuth.instance.signIn(credential);
    print("User signed in: ${user.uid}");
  } catch (e) {
    print("Error: $e");
  }
}

第三方认证

Future<void> signInWithThirdParty() async {
  try {
    // 使用第三方账号登录,例如华为账号
    AuthCredential credential = HwIdAuthProvider.credential();

    // 登录
    User user = await AGConnectAuth.instance.signIn(credential);
    print("User signed in: ${user.uid}");
  } catch (e) {
    print("Error: $e");
  }
}

5. 用户管理

获取当前用户

Future<void> getCurrentUser() async {
  User? user = AGConnectAuth.instance.currentUser;
  if (user != null) {
    print("Current user: ${user.uid}");
  } else {
    print("No user signed in");
  }
}

退出登录

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

删除用户

Future<void> deleteUser() async {
  await AGConnectAuth.instance.deleteUser();
  print("User deleted");
}

6. 错误处理

在使用 agconnect_auth 时,可能会遇到各种错误(如网络错误、验证码错误等)。建议在使用 try-catch 块捕获异常并进行处理。

try {
  // 认证操作
} catch (e) {
  print("Error: $e");
}
回到顶部