flutter_login_vk 0.1.0+3

  • Readme
  • Changelog
  • Example
  • Installing
  • new72

flutter_login_vk #

pub package

Flutter Plugin to login via VK.com.

Easily add VK login feature in your application. User profile information included.

SDK version #

VK SDK version, used in plugin:

Minimum requirements #

  • iOS 9.0 and higher.
  • Android 4.1 and newer (SDK 16).

⚠️ If your project was create with Flutter pre 1.12 you should upgrade it to the Android embedding v2. See https://flutter.dev/go/android-project-migration

Getting Started #

To use this plugin:

  1. add flutter_login_vk as a dependency in your pubspec.yaml file;
  2. create an app on VK.com
  3. setup android;
  4. setup ios;
  5. additional VK.com app setup;
  6. use plugin in application.

See documentation on VK.com for full information:

And here is instructions in Russian if it's your native language (русская версия).

App on VK.com #

Create an app on VK.com https://vk.com/editapp?act=create

  1. Enter "Title".
  2. Select Standalone app as "Platform".
  3. Click "Connect app".

An application will be created. Now select tab "Settings" and copy "App ID" (referenced as [APP_ID] in this readme).

App settings for Android

  1. Set Package name for Android - your package name for Android application (attribute package in AndroidManifest.xml).

  2. Set Main activity for Android - your main activity class (with package). By default it would be com.yourcompany.yourapp.MainActivity.

  3. To fill up Signing certificate fingerprint for Android you should create SHA1 fingerprint as described in the documentation (without SHA1: prefix). Add fingerprints for debug and release certificates. Note: if your application uses Google Play App Signing than you should get certificate SHA-1 fingerprint from Google Play Console.

    ⚠️ Important! You should add fingerprints for every build variants. E.g. if you have CI/CD which build APK for testing with it's own cerificate (it may be auto generated debug cetificate or some another) than you should add it's fingerprint too.

  4. Click "Save".

App settings for iOS

  1. Add your Bundle Identifier - set App Bundle ID for iOS (you can find it in Xcode: Runner - Target Runner - General, section Identity, field Bundle Identifier).
  2. Also set App ID for iOS, it's you SKU (you can find it in App Store Connect: My Apps - {Your application} - App Store - App Information, section "General Information"). Mostly often is't the same as bundle ID.
  3. Click "Save".

Android #

Edit AndroidManifest.xml (android/app/src/main/AndroidManifest.xml):

  1. Add the INTERNET permission in the root of <manifest>, if you haven't (probably you have):
<uses-permission android:name="android.permission.INTERNET" />
  1. Add an activity to the section application:
<activity android:name="com.vk.sdk.VKServiceActivity"
    android:label="ServiceActivity"
    android:theme="@style/VK.Transparent" />

See full AndroidManifest.xml in example.

iOS #

Configure Info.plist (ios/Runner/Info.plist). You can edit it as a text file from your IDE, or you can open project (ios/Runner.xcworkspace) in Xcode.

  1. In Xcode right-click on Info.plist, and choose Open As Source Code.
  2. Copy and paste the following XML snippet into the body of your file (<dict>...</dict>), replacing [APP_ID] with your application id:
<key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>vk[APP_ID]</string>
  </array>
  </dict>
</array>
  1. Also add to Info.plist body (<dict>...</dict>):
<key>LSApplicationQueriesSchemes</key> 
<array> 
    <string>vk</string> 
    <string>vk-share</string> 
    <string>vkauthorize</string> 
</array>

See full Info.plist in example.

⚠️ NOTE. Check if you already have CFBundleURLTypes or LSApplicationQueriesSchemes keys in your Info.plist. If you have, you should merge their values, instead of adding a duplicate key.

If you want to use scope=nohttps, which we strongly do not recommend, you should also add NSAppTransportSecurity, see the documentation.

Additional VK.com app setup #

Go to My Apps and click "Manage" on your app.

On tab "Information" you should:

  1. Enter "Description".
  2. Select a suitable "Category".
  3. Upload small icon "32x32 icon".
  4. Click "Save".
  5. Upload "Square banner" and "A square banner for catalog" - user can see it.

Setup other settings if you need it.

Than go to "Setting" tab and turn on application: change "App status" from Application off to Application on and visible to all.

Click "Save".

Usage in application #

First, you should create an instance of VKLogin. Than, before any method call or checking accessToken, you should initialize VK SDK with your application id ([APP_ID]):

final vk = VKLogin();
final appId = '7503887'; // Your application ID
await vk.initSdk(appId);

Now you can use the plugin.

Features:

  • log in via VK.com;
  • get access token;
  • get user profile;
  • get user email;
  • check if logged in;
  • log out.

Sample code:

import 'package:flutter_login_vk/flutter_login_vk.dart';

// Create an instance of VKLogin
final vk = VKLogin();

// Initialize
await vk.initSdk('7503887');

// Log in
final res = await vk.logIn(permissions: [
  VKScope.email,
  VKScope.friends,
]);

// Check result
if (res.isValue) {
    // There is no error, but we don't know yet
    // if user loggen in or not.
    // You should check isCanceled
    final VKLoginResult data = res.asValue.value;

    if (res.isCanceled) {
        // User cancel log in
    } else {
        // Logged in

        // Send access token to server for validation and auth
        final VKAccessToken accessToken = res.accessToken;
        print('Access token: ${accessToken.token}');
    
        // Get profile data
        final profile = await fb.getUserProfile();
        print('Hello, ${profile.firstName}! You ID: ${profile.userId}');

        // Get email (since we request email permissions)
        final email = await fb.getUserEmail();
        print('And your email is $email');
    }
} else {
    // Log in failed
    final errorRes = res.asError;
    print('Error while log in: ${errorRes.error}');
}

Initialization notes

When you call initSdk(), plugin try to restore previous session. If token has been expired - it will be refreshed.

Also, during restoring, log in screen may be shown to user (only if user was logged in).

In additional, you can pass to initSdk() required scope, and if current user session doesn't provide it - user will be logged out.

Also you can specify API version to use, but you shouldn't.

Next release #

0.1.0+3 - 2020-07-04 #

  • Readme: Upgrade to the Android embedding v2.
  • Readme: Typos and fixes.
  • Readme: Link to instruction in Russian.

0.1.0+1 - 2020-06-15 #

  • Initial release: log in, get profile information, get email, log out.

example/lib/main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_vk/flutter_login_vk.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  final plugin = VKLogin(debug: true);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _sdkVersion;
  VKAccessToken _token;
  VKUserProfile _profile;
  String _email;
  bool _sdkInitialized = false;

  @override
  void initState() {
    super.initState();

    _getSdkVersion();
    _initSdk();
  }

  @override
  Widget build(BuildContext context) {
    final isLogin = _token != null && _profile != null;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Login via VK example'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(vertical: 18.0, horizontal: 8.0),
          child: Builder(
            builder: (context) => Center(
              child: Column(
                children: <Widget>[
                  if (_sdkVersion != null) Text("SDK v$_sdkVersion"),
                  if (isLogin)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 10),
                      child: _buildUserInfo(context, _profile, _token, _email),
                    ),
                  isLogin
                      ? OutlineButton(
                          child: Text('Log Out'),
                          onPressed: _onPressedLogOutButton,
                        )
                      : OutlineButton(
                          child: Text('Log In'),
                          onPressed: () => _onPressedLogInButton(context),
                        ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context, VKUserProfile profile,
      VKAccessToken accessToken, String email) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('User: '),
        Text(
          '${profile.firstName} ${profile.lastName}',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        Text(
          'Online: ${profile.online}, Online mobile: ${profile.onlineMobile}',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        if (profile.photo200 != null) Image.network(profile.photo200),
        Text('AccessToken: '),
        Container(
          child: Text(
            accessToken.token,
            softWrap: true,
          ),
        ),
        Text('Created: ${accessToken.created}'),
        Text('Expires in: ${accessToken.expiresIn}'),
        if (email != null) Text('Email: $email'),
      ],
    );
  }

  void _onPressedLogInButton(BuildContext context) async {
    final res = await widget.plugin.logIn(scope: [
      VKScope.email,
    ]);

    if (res.isError) {
      Scaffold.of(context).showSnackBar(
        SnackBar(
          content: Text('Log In failed: ${res.asError.error}'),
        ),
      );
    } else {
      final loginResult = res.asValue.value;
      if (!loginResult.isCanceled) _updateLoginInfo();
    }
  }

  void _onPressedLogOutButton() async {
    await widget.plugin.logOut();
    _updateLoginInfo();
  }

  void _initSdk() async {
    await widget.plugin.initSdk('7503887');
    _sdkInitialized = true;
    _updateLoginInfo();
  }

  void _getSdkVersion() async {
    final sdkVersion = await widget.plugin.sdkVersion;
    setState(() {
      _sdkVersion = sdkVersion;
    });
  }

  void _updateLoginInfo() async {
    if (!_sdkInitialized) return;

    final plugin = widget.plugin;
    final token = await plugin.accessToken;
    final profileRes = token != null ? await plugin.getUserProfile() : null;
    final email = token != null ? await plugin.getUserEmail() : null;

    setState(() {
      _token = token;
      _profile = profileRes?.asValue?.value;
      _email = email;
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_login_vk: ^0.1.0+3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_login_vk/flutter_login_vk.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
44
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
72
Learn more about scoring.

We analyzed this package on Jul 4, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:flutter_login_vk/flutter_login_vk.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:flutter_login_vk/flutter_login_vk.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:flutter_login_vk/flutter_login_vk.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:flutter_login_vk/flutter_login_vk.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [flutter_login_vk] that is in a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
async ^2.3.0 2.4.1
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test