Flutter LinkedIn登录插件easy_linkedin_login的使用

Flutter LinkedIn登录插件easy_linkedin_login的使用

重要信息

  • 使用的是最新版的LinkedIn登录产品 Sign In with LinkedIn using OpenID Connect
  • LinkedIn产品 Sign In with LinkedIn 已经废弃。
  • 如果仍然需要使用废弃的产品 Sign In with LinkedIn,请参考版本 1.0.3

步骤

  1. 在LinkedIn开发者控制台创建应用。
  2. 在产品页面添加 Sign In with LinkedIn using OpenID Connect
  3. 在认证页面添加 Authorized redirect URL
  4. 获取 clientIdclientSecretredirectUrl

开始

创建包含密钥的 LinkedInConfig 类。

final config = LinkedInConfig(
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUrl: 'YOUR_REDIRECT_URL',
);

标准组件

标准的LinkedIn按钮用于登录。此组件可以自定义。

LinkedInStandardButton(
  config: config,
  destroySession: false,
  onError: (error) => log('Error: ${error.message}'),
  onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
  onGetUserProfile: (user) => log('User: ${user.name}'),
),

注意:

  • 可以使用 mini 属性来使用 Small Linkedin Icon Button

自定义组件

带有自定义组件的LinkedIn按钮。

LinkedInCustomButton(
  config: config,
  destroySession: false,
  onError: (error) => log('Error: ${error.message}'),
  onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
  onGetUserProfile: ( user) => log('User: ${ user.name}'),
  child: Text('Click Here to Login with linkedin'),
),

注意:

  • destroySession 设置为 true 会清除Linkedin登录会话。

自定义化

带有自定义化的LinkedIn标准按钮。

LinkedInStandardButton(
  config: config,
  appbar: MyPreferredSizeWidget(),
  iconAssetPath: "/assets/my_custom_icon.png",
  iconWidth: 30,
  iconHeight: 30,
  destroySession: false,
  onError: (error) => log('Error: ${error.message}'),
  onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
  onGetUserProfile: (user) => log('User: ${user.name}'),
),

LinkedInStandardButton(
  config: config,
  mini: true,
  destroySession: false,
  onError: (error) => log('Error: ${error.message}'),
  onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
  onGetUserProfile: (user) => log('User: ${user.name}'),
),

LinkedInCustomButton(
  config: config,
  appbar: MyPreferredSizeWidget(),
  destroySession: false,
  onError: (error) => log('Error: ${error.message}'),
  onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
  onGetUserProfile: (user) => log('User: ${user.name}'),
  child: Container(
    decoration: BoxDecoration(
      color: Colors.blueAccent,
      borderRadius: BorderRadius.circular(8),
    ),
    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 13),
    child: Text(
      'Click Here to Login with linkedin',
      style: TextStyle(color: Colors.white),
    ),
  ),
),

截图

Home

示例代码

import 'dart:developer';

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

final config = LinkedInConfig(
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUrl: 'YOUR_REDIRECT_URL',
);

void main() => runApp(const MyApp());

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

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter LinkedIn demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('LinkedIn Authorization'),
        ),
        body: const LinkedInProfileExamplePage(),
      ),
    );
  }
}

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

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

class _LinkedInProfileExamplePageState
    extends State<LinkedInProfileExamplePage> {
  UserObject? user;
  bool logoutUser = false;

  void setUser(LinkedInUserModel u) {
    setState(() {
      user = UserObject(
        firstName: u.givenName ?? 'N/A',
        lastName: u.familyName ?? 'N/A',
        email: u.email ?? 'N/A',
        profileImageUrl: u.picture ?? ' N/A',
      );
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          LinkedInStandardButton(
            config: config,
            destroySession: logoutUser,
            onError: (error) => log('Error: ${error.message}'),
            onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
            onGetUserProfile: setUser,
            mini: true,
          ),
          LinkedInStandardButton(
            config: config,
            destroySession: logoutUser,
            onError: (error) => log('Error: ${error.message}'),
            onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
            onGetUserProfile: setUser,
          ),
          LinkedInCustomButton(
            config: config,
            destroySession: logoutUser,
            onError: (error) => log('Error: ${error.message}'),
            onGetAuthToken: (data) => log('Access token ${data.accessToken!}'),
            onGetUserProfile: setUser,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.blueAccent,
                borderRadius: BorderRadius.circular(8),
              ),
              padding: EdgeInsets.symmetric(horizontal: 20, vertical: 13),
              child: Text(
                'Click Here to Login with linkedin',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('First: ${user?.firstName} '),
              Text('Last: ${user?.lastName} '),
              Text('Email: ${user?.email}'),
              Text('Profile image: ${user?.profileImageUrl}'),
            ],
          ),
        ],
      ),
    );
  }
}

class UserObject {
  UserObject(
      {required this.firstName,
      required this.lastName,
      required this.email,
      required this.profileImageUrl});

  String firstName, lastName, email, profileImageUrl;
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用easy_linkedin_login插件来实现LinkedIn登录功能的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了easy_linkedin_login依赖项:

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

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

接下来,你需要在LinkedIn开发者平台上创建一个应用,并获取客户端ID和客户端密钥。确保你已经配置了LinkedIn应用的回调URL,以便在用户成功登录后重定向回你的应用。

以下是一个完整的Flutter应用示例,展示了如何使用easy_linkedin_login插件:

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

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

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

class LinkedInLoginScreen extends StatefulWidget {
  @override
  _LinkedInLoginScreenState createState() => _LinkedInLoginScreenState();
}

class _LinkedInLoginScreenState extends State<LinkedInLoginScreen> {
  final LinkedIn _linkedIn = LinkedIn(
    clientId: '你的LinkedIn客户端ID',
    clientSecret: '你的LinkedIn客户端密钥',
    redirectUri: '你的LinkedIn回调URL',
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LinkedIn Login Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              String authorizationCode = await _linkedIn.login();
              print('Authorization Code: $authorizationCode');

              // 使用authorizationCode去LinkedIn获取访问令牌
              // 这通常需要在你的后端服务器上进行,因为需要客户端密钥
              // 下面是一个简单的示例,假设你已经在后端处理了令牌获取
              // String accessToken = await getAccessTokenFromBackend(authorizationCode);

              // 接下来,你可以使用访问令牌来访问LinkedIn API
              // 例如,获取用户信息
              // LinkedInUser user = await _linkedIn.getUserInfo(accessToken);
              // print('LinkedIn User: $user');

            } catch (e) {
              print('LinkedIn login error: $e');
            }
          },
          child: Text('Login with LinkedIn'),
        ),
      ),
    );
  }
}

注意

  1. 在实际使用中,你不应该在客户端代码中直接处理客户端密钥。你应该将authorizationCode发送到你的后端服务器,然后在后端使用客户端密钥和authorizationCode来交换访问令牌。
  2. LinkedIn类的login方法会启动一个WebView来显示LinkedIn的登录页面。用户登录后,它将返回一个authorizationCode
  3. 示例中的getAccessTokenFromBackend方法是一个假设的方法,你需要根据你的后端实现来替换它。

确保你按照LinkedIn开发者文档的要求配置了你的应用,并正确设置了回调URL。此外,由于LinkedIn API的变更,某些功能可能需要额外的权限或配置。

希望这个示例能帮助你在Flutter项目中实现LinkedIn登录功能!

回到顶部