google_sign_in_dartio 0.0.6

  • Readme
  • Changelog
  • Example
  • Installing
  • 66

google_sign_in_dartio #

A Flutter package that implements Google Sign In in pure Dart. This package is compatible with google_sign_in plugin and works on all platforms Flutter supports.

Getting Started #

Install and initialization #

  1. Depend on it
     dependencies:
       google_sign_in: ^4.1.4
       google_sign_in_dartio: ^0.0.1
    
  2. Run flutter pub get
  3. Import
     import 'package:google_sign_in/google_sign_in.dart';
     import 'package:google_sign_in_dartio/google_sign_in_dartio.dart';
    
  4. Register the package
     import 'package:flutter/material.dart';
     import 'package:google_sign_in/google_sign_in.dart';
     import 'package:google_sign_in_dartio/google_sign_in_dartio.dart';
    
     void main() {
       if (isDesktop) {
         GoogleSignInPlatform.register(clientId: <clientId>);
       }
    
       runApp(MyApp());
     }
    
    Note: You might want to await for the register method to finish before calling any GoogleSignIn methods when your app starts.

Usage #

You can use the normal GoogleSignIn methods.

final GoogleSignInAccount account = await GoogleSignIn().signIn();

Obtain a Client ID for your Desktop app #

  1. Go to the Google Cloud Platform console and select you project
  2. Go to APIs & Service -> Credentials
  3. Create new credentials for your app by selecting CREATE CREDENTIALS and then OAuth client ID
  4. Select Other as Application type, give it a name (eg. macOS) and then click Create

Provide a code exchange endpoint #

The user accessToken expires after about one hour, after witch you need to ask the user to login again. If you want to keep the user logged in, you need to deploy a oAuth code exchange endpoint. Once you have your endpoint you can register the package like this.

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_sign_in_dartio/google_sign_in_dartio.dart';

void main() {
  if (isDesktop) {
    GoogleSignInPlatform.register(
        clientId: <clientId>, 
        exchangeEndpoint: <endpoint>,
    );
  }

  runApp(MyApp());
}

See instruction on how to deploy a code exchange endpoint.

0.0.6 #

  • changed the name from GoogleSignInPlatform to GoogleSignInDart to match other packages

0.0.5 #

  • fix passing the scopes when present

0.0.4+1 #

  • fix logic bug

0.0.4 #

  • add default scopes openid, email, profile

0.0.3 #

  • remove isDesktop

0.0.2+1 #

  • update readme

0.0.2 #

  • update readme
  • rename from google_sign_in_dart to google_sign_in_dartio due to the fact that the name was not available in pub

0.0.1 #

  • Initial release.

example/lib/main.dart

// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:convert' show json;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_sign_in_dartio/google_sign_in_dartio.dart';
import 'package:http/http.dart' as http;

import 'platform_js.dart' if (dart.library.io) 'platform_io.dart';

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
    'profile',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

Future<void> main() async {
  if (isDesktop) {
    await GoogleSignInDart.register(
      exchangeEndpoint:
          'https://us-central1-flutter-sdk.cloudfunctions.net/authHandler',
      clientId:
          '233259864964-go57eg1ones74e03adlqvbtg2av6tivb.apps.googleusercontent.com',
    );
  }

  runApp(
    MaterialApp(
      title: 'Google Sign In',
      home: SignInDemo(),
    ),
  );
}

class SignInDemo extends StatefulWidget {
  @override
  State createState() => SignInDemoState();
}

class SignInDemoState extends State<SignInDemo> {
  GoogleSignInAccount _currentUser;
  String _contactText;

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
      setState(() {
        _currentUser = account;
      });
      if (_currentUser != null) {
        _handleGetContact();
      }
    });

    _googleSignIn.signInSilently();
  }

  Future<void> _handleGetContact() async {
    setState(() {
      _contactText = 'Loading contact info...';
    });
    final http.Response response = await http.get(
      'https://people.googleapis.com/v1/people/me/connections'
      '?requestMask.includeField=person.names',
      headers: await _currentUser.authHeaders,
    );
    if (response.statusCode != 200) {
      setState(() {
        _contactText = 'People API gave a ${response.statusCode} '
            'response. Check logs for details.';
      });
      print('People API ${response.statusCode} response: ${response.body}');
      return;
    }
    final Map<String, dynamic> data = json.decode(response.body);
    final String namedContact = _pickFirstNamedContact(data);
    setState(() {
      if (namedContact != null) {
        _contactText = 'I see you know $namedContact!';
      } else {
        _contactText = 'No contacts to display.';
      }
    });
  }

  String _pickFirstNamedContact(Map<String, dynamic> data) {
    final List<dynamic> connections = data['connections'];
    final Map<String, dynamic> contact = connections?.firstWhere(
      (dynamic contact) => contact['names'] != null,
      orElse: () => null,
    );
    if (contact != null) {
      final Map<String, dynamic> name = contact['names'].firstWhere(
        (dynamic name) => name['displayName'] != null,
        orElse: () => null,
      );
      if (name != null) {
        return name['displayName'];
      }
    }
    return null;
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() => _googleSignIn.disconnect();

  Widget _buildBody() {
    if (_currentUser != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: kIsWeb
                ? GoogleUserCircleAvatar(
                    identity: _currentUser,
                  )
                : ClipOval(
                    child: Image.network(
                      _currentUser.photoUrl ??
                          'https://lh3.googleusercontent.com/a/default-user=s160-c',
                    ),
                  ),
            title: Text(_currentUser.displayName ?? ''),
            subtitle: Text(_currentUser.email ?? ''),
          ),
          const Text('Signed in successfully.'),
          Text(_contactText ?? ''),
          RaisedButton(
            onPressed: _handleSignOut,
            child: const Text('SIGN OUT'),
          ),
          RaisedButton(
            onPressed: _handleGetContact,
            child: const Text('REFRESH'),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text('You are not currently signed in.'),
          RaisedButton(
            onPressed: _handleSignIn,
            child: const Text('SIGN IN'),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Sign In'),
      ),
      body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: _buildBody(),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  google_sign_in_dartio: ^0.0.6

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:google_sign_in_dartio/google_sign_in_dartio.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
36
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
66
Learn more about scoring.

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

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
crypto ^2.1.3 2.1.5
flutter 0.0.0
google_sign_in ^4.1.4 4.5.1
google_sign_in_platform_interface ^1.0.4 1.1.2
http ^0.12.0+4 0.12.1
meta ^1.0.4 1.1.8
shared_preferences ^0.5.6+2 0.5.7+3
shared_preferences_macos ^0.0.1+6 0.0.1+9
url_launcher ^5.4.2 5.4.10
url_launcher_macos ^0.0.1+4 0.0.1+7
Transitive dependencies
charcode 1.1.3
collection 1.14.12
convert 2.1.1
flutter_web_plugins 0.0.0
google_sign_in_web 0.9.1+1
http_parser 3.1.4
js 0.6.1+1
matcher 0.12.6
path 1.7.0
pedantic 1.9.0
platform_detect 1.4.0
plugin_platform_interface 1.0.2
pub_semver 1.4.4
quiver 2.1.3
shared_preferences_platform_interface 1.0.4
shared_preferences_web 0.1.2+7
sky_engine 0.0.99
source_span 1.7.0
stack_trace 1.9.3
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
url_launcher_platform_interface 1.0.7
url_launcher_web 0.1.1+6
vector_math 2.0.8
Dev dependencies
flutter_test