Flutter Yandex登录插件flutter_login_yandex的使用

Flutter Yandex登录插件flutter_login_yandex的使用

概述

flutter_login_yandex 是一个用于在iOS和Android平台上通过Yandex LoginSDK进行授权的Flutter插件。

开始使用

首先,你需要注册一个Yandex OAuth应用,请参考官方文档(链接已去掉)。

Android 配置

在你的 android/app/build.gradle 文件的 defaultConfig 部分添加以下内容,并将 yourClientId 替换为你的Yandex OAuth应用的客户端ID:

defaultConfig {
    applicationId "com.example.flutter_login_yandex_example"
    minSdkVersion flutter.minSdkVersion
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    // 添加以下行
    manifestPlaceholders = [YANDEX_CLIENT_ID:"yourClientId"]
}
iOS 配置

在你的 Info.plist 文件中添加以下内容,并将 yourClientId 替换为你的Yandex OAuth应用的客户端ID:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>yandexauth</string>
    <string>yandexauth2</string>
    <string>yandexauth4</string>
</array>
<key>YAClientId</key>
<string>yourClientId</string>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>YandexLoginSDK</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>yxyourClientId</string>
        </array>
    </dict>
</array>

AppDelegate.swift 中添加以下代码:

@available(iOS 8.0, *)
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
   YXLSdk.shared.processUserActivity(userActivity)
   return true
}

// Application delegate
override public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return YXLSdk.shared.handleOpen(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String)
}

如果已有 OpenURL 处理器,需要将其与现有代码合并。

还需设置权限,添加“关联域名”功能,并输入替换后的域名:

applinks:yxyourClientId.oauth.yandex.ru

如果有编译时的弃用错误,可以使用 @MariyanskiDev 的修复方法。在 Podfile 的目标中添加:

pod 'YandexLoginSDK', :git => 'https://github.com/MariyanskiDev/yandex-login-sdk-ios', :branch => 'depreciation_fix'

应用中的使用

简单示例如下:

final flutterLoginYandexPlugin = FlutterLoginYandex();
final response = await _flutterLoginYandexPlugin.signIn();
saveToken(response['token'] as String);

完整示例 Demo

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_login_yandex/flutter_login_yandex.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> {
  String _token = 'empty';
  final _flutterLoginYandexPlugin = FlutterLoginYandex();

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Token: $_token\n', textAlign: TextAlign.center),
              InkWell(
                onTap: () async {
                  // 调用signIn方法进行登录
                  final response = await _flutterLoginYandexPlugin.signIn();
                  if (response != null) {
                    setState(() {
                      if (response['token'] != null) {
                        _token = response['token'] as String;
                      } else {
                        _token = response['error'] as String;
                      }
                    });
                  }
                },
                child: const Padding(padding: EdgeInsets.all(15), child: Text('点击登录')),
              ),
              if (Platform.isIOS)
                InkWell(
                  onTap: () async {
                    // 调用signOut方法进行登出
                    final response = await _flutterLoginYandexPlugin.signOut();
                    setState(() {
                      _token = '';
                    });
                  },
                  child: const Padding(padding: EdgeInsets.all(15), child: Text('退出登录')),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用flutter_login_yandex插件来实现Yandex登录功能的代码示例。这个示例假设你已经有一个Flutter项目,并且已经配置好了Yandex OAuth 2.0客户端。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_login_yandex: ^最新版本号  # 请替换为实际的最新版本号

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

2. 配置Yandex OAuth 2.0

在Yandex开发者控制台中创建一个OAuth 2.0应用,并获取客户端ID和客户端密钥。确保你已经设置了重定向URI,通常这个URI会是你的应用的自定义URL scheme。

3. 使用flutter_login_yandex插件

接下来,在你的Flutter应用中实现Yandex登录功能。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Yandex Login Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: YandexLoginScreen(),
    );
  }
}

class YandexLoginScreen extends StatefulWidget {
  @override
  _YandexLoginScreenState createState() => _YandexLoginScreenState();
}

class _YandexLoginScreenState extends State<YandexLoginScreen> {
  final YandexLogin _yandexLogin = YandexLogin(
    clientId: '你的Yandex客户端ID',
    clientSecret: '你的Yandex客户端密钥',
    redirectUri: Uri.parse('你的重定向URI'),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Yandex Login Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              final result = await _yandexLogin.login(context);
              if (result != null) {
                // 登录成功,处理结果
                print('Access Token: ${result.accessToken}');
                print('User ID: ${result.userId}');
                print('User Display Name: ${result.displayName}');
                // 你可以在这里保存token或者进行其他操作
              }
            } catch (e) {
              // 处理错误
              print('Error: $e');
            }
          },
          child: Text('Login with Yandex'),
        ),
      ),
    );
  }
}

4. 处理登录结果

在上面的代码中,当用户点击登录按钮时,会触发_yandexLogin.login(context)方法。这个方法会打开一个WebView来让用户进行Yandex登录。一旦用户成功登录,你会得到一个YandexLoginResult对象,其中包含了访问令牌(accessToken)、用户ID(userId)和用户的显示名称(displayName)等信息。

注意事项

  • 确保你的应用已经在Yandex开发者控制台中配置了正确的重定向URI。
  • 在实际的生产环境中,不要将客户端密钥硬编码在应用中。考虑使用环境变量或安全的密钥管理服务来存储敏感信息。
  • 处理用户数据和访问令牌时要遵守Yandex的使用政策和隐私条款。

希望这个示例能帮助你顺利地在Flutter应用中实现Yandex登录功能。

回到顶部