Google Sign-In for Flutter: A Comprehensive Guide

Published on by Flutter News Hub

Google Sign-In for Flutter: A Comprehensive Guide

Introduction

Google Sign-In is a Flutter plugin that allows your app to authenticate users with Google. This enables features such as single sign-on, user profiles, and access to Google services like Gmail and Drive.

Platform Integration

Android

  • Register your application with Google.
  • Enable the required OAuth APIs using the Google Cloud Platform API manager.
  • Complete the OAuth consent screen fields.

iOS

macOS

Web

  • Separate Authentication from Authorization (Flutter apps must detect granted scopes and validate their validity).
  • Read more at the google_sign_in_web package.

Usage

Import

Add the following to your pubspec.yaml file:

dependencies:
  google_sign_in: "^6.2.0"

Initialization

import 'package:google_sign_in/google_sign_in.dart';

const List scopes = ['email', 'https://www.googleapis.com/auth/contacts.readonly', ];
final GoogleSignIn _googleSignIn = GoogleSignIn(
  // Optional clientId
  // clientId: 'your-client_id.apps.googleusercontent.com',
  scopes: scopes,
);

Authentication

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

Web

In the web, use the Google Sign In button instead of signIn.

GoogleSignInButton(
  onPressed: () async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print(error);
    }
  },
)

Working with Scopes and Incremental Authorization

Checking Granted Scopes

final bool isAuthorized = account != null;

Web Only:

if (kIsWeb && account != null) {
  isAuthorized = await _googleSignIn.canAccessScopes(scopes);
}

Requesting Additional Scopes

Future _handleAuthorizeScopes() async {
  final bool isAuthorized = await _googleSignIn.requestScopes(scopes);
  if (isAuthorized) {
    unawaited(_handleGetContact(_currentUser!));
  }
}

Authorization Expiration

In the web, the access token expires after 3600 seconds (one hour). Handle failed REST requests and update the UI to prompt the user for re-authorization.

Example

import 'package:google_sign_in/google_sign_in.dart';

class LoginPage extends StatelessWidget {
  final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: ['email', 'https://www.googleapis.com/auth/contacts.readonly', ],
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GoogleSignInButton(
          onPressed: () async {
            try {
              await _googleSignIn.signIn();
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => HomePage()),
              );
            } catch (error) {
              print(error);
            }
          },
        ),
      ),
    );
  }
}

Conclusion

Google Sign-In provides a convenient and easy-to-use solution for authenticating users in your Flutter app. Remember to handle incremental authorization and scope management, especially for web applications.

Flutter News Hub