Flutter苹果账号登录插件sign_in_with_apple_native的使用

Flutter苹果账号登录插件sign_in_with_apple_native的使用

获取开始

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  sign_in_with_apple_native: ^0.0.1
2. 导入插件

在 Dart 文件中导入插件:

import 'package:sign_in_with_apple_native/sign_in_with_apple_native.dart';
3. 使用插件
3.1 前提条件

为了使用“Sign in with Apple”,你需要在你的应用中启用“Sign in with Apple”功能。为此,请在 Xcode 中打开你的项目,选择项目导航器中的项目,选择你的目标,然后打开“Signing & Capabilities”标签。点击“+ Capability”按钮,并从列表中选择“Sign in with Apple”。

3.2 检查是否可用

由于插件仅适用于 iOS 13 及以上版本,该方法总是返回 true

final isAvailable = await SignInWithAppleNative.isAvailable();
3.3 检查凭证状态

使用 ASAuthorizationAppleIDProvider.getCredentialState 来检查凭证的状态。这是一个本地的、低成本的、非网络调用,由 Apple ID 系统启用,保持设备上的 Apple ID 状态与 Apple 服务器同步。

final state = await SignInWithAppleNative.credentialState;
3.4 请求凭证

使用 ASAuthorizationController.performRequests 来请求用户凭证。

SignInWithAppleButton(
  onPressed: () async {
    final credential = await SignInWithAppleNative.authorize();
    print(credential);
  },
)
3.5 在服务器上验证凭证

使用 identityTokenauthorizationCode 在你的服务器上验证凭证。更多信息请参见 验证用户

示例

以下是一个完整的示例应用,展示了如何使用 Sign in with Apple 按钮。

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

import 'package:flutter/services.dart';
import 'package:sign_in_with_apple_native/sign_in_with_apple_native.dart';
import 'package:sign_in_with_apple_native/sign_in_with_apple_native_button.dart';
import 'package:sign_in_with_apple_native/types/authorization_scope.dart';
import 'package:sign_in_with_apple_native/types/credential_state.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isAvailable = false;
  final _signInWithAppleNativePlugin = SignInWithAppleNative();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
    _signInWithAppleNativePlugin.onAuthenticationRevoked.listen((event) {
      setState(() {});
    });
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    bool isAvailable;
    // 平台消息可能会失败,所以我们使用 try/catch PlatformException。
    // 我们还处理了消息可能返回 null 的情况。
    try {
      isAvailable = await _signInWithAppleNativePlugin.isAvailable();
    } on PlatformException {
      isAvailable = false;
    }

    // 如果小部件在异步平台消息飞行时从树中移除,我们希望丢弃回复而不是调用
    // setState 来更新我们的不存在的外观。
    if (!mounted) return;

    setState(() {
      _isAvailable = isAvailable;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Column(children: [
            Text('是否支持“Sign In with Apple”: $_isAvailable\n'),
            FutureBuilder(
                future: _signInWithAppleNativePlugin.credentialState,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    if (snapshot.data != CredentialState.authorized) {
                      return SizedBox(
                        width: MediaQuery.of(context).size.width * 0.8,
                        height: 60,
                        child: SignInWithAppleNativeButton(
                          onPressed: _authorize,
                        ),
                      );
                    }
                    return Text('凭证状态: ${snapshot.data}');
                  } else if (snapshot.hasError) {
                    return Text('凭证状态: ${snapshot.error}');
                  } else {
                    return const Text('凭证状态: 加载中...');
                  }
                }),
          ]),
        ),
      ),
    );
  }

  Future<void> _authorize() async {
    try {
      final authorizationResult = await _signInWithAppleNativePlugin.authorize(
        requestedScopes: [
          AuthorizationScope.email,
          AuthorizationScope.fullName,
        ],
      );
      print('authorizationResult: ${authorizationResult.idToken}');
      setState(() {});
    } catch (e) {
      print('authorizationResult: 空');
    }
  }
}

更多关于Flutter苹果账号登录插件sign_in_with_apple_native的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter苹果账号登录插件sign_in_with_apple_native的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,sign_in_with_apple_native 插件是一个用于实现苹果账号登录的插件。它允许用户使用他们的 Apple ID 登录你的应用程序,并获取相关的用户信息。以下是使用 sign_in_with_apple_native 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  sign_in_with_apple_native: ^1.0.0  # 请检查最新版本

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

2. 配置 iOS 项目

为了在 iOS 项目中使用 Apple 登录,你需要进行以下配置:

  1. 启用 Apple 登录功能

    • 打开 Xcode,选择你的 iOS 项目。
    • Signing & Capabilities 选项卡中,点击 + Capability 按钮。
    • 选择 Sign in with Apple 并添加。
  2. 配置 Info.plist

    • 打开 ios/Runner/Info.plist 文件。
    • 添加以下内容:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>YOUR_BUNDLE_ID</string>
        </array>
    </dict>
</array>
<key>CFBundleLocalizations</key>
<array>
    <string>en</string>
</array>

3. 使用插件进行 Apple 登录

在你的 Flutter 代码中,你可以使用 SignInWithAppleNative 类来实现 Apple 登录。以下是一个简单的示例:

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

class AppleSignInPage extends StatelessWidget {
  Future<void> _signInWithApple() async {
    try {
      final result = await SignInWithAppleNative.signIn();

      if (result != null) {
        // 登录成功,处理用户信息
        print('User ID: ${result.userIdentifier}');
        print('Email: ${result.email}');
        print('Given Name: ${result.givenName}');
        print('Family Name: ${result.familyName}');
      } else {
        // 用户取消登录
        print('User canceled the login');
      }
    } catch (e) {
      // 处理错误
      print('Error: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Apple Sign In'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _signInWithApple,
          child: Text('Sign in with Apple'),
        ),
      ),
    );
  }
}
回到顶部