"Login Demo" app which shows how to use google sign in Android and iOS using Flutter.

Overview

⚠️ ARCHIVED: This repository is using Flutter 1.7 for the sample app. You can find the latest version of the similar implementation on this new repo. The new version is using Flutter 2.0 (stable) with null safety enabled, and is tested on Android, iOS & Web.

The updated Medium article for "Flutter: Implementing Google Sign In" is here.


Flutter Google Sign In using Firebase

codemagic

Checkout my Medium article "Flutter: Implementing Google Sign In".

In this app, I have implemented Google Sign In using Firebase for both Android and iOS, fixing all the issues with the latest Flutter updates. To understand how to fix all the Firebase issues in Flutter make sure you check out my Medium article.

NOTE: The project is tested on Flutter 1.7 (stable) and using all the latest versions of the plugins.

Project versions

There are three versions of this project available:

  • Simple Google Sign In (master)
  • Combined with Auto Login (auto_login)
  • Combined with Local Authentication using Biometric (local_auth)

Using this app

If you want to clone and use this app, then you have to complete the following steps:

Step 1: Generate the SHA-1

Use the following command to generate SHA-1:

keytool -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

Step 2: Complete the Firebase setup

First of all, complete the whole Firebase setup for both Android and iOS. You will get two files while doing the setup, one for each platform. You have to place the google-services.json & GoogleService-Info.plist files in the respective directory of each platform. For more info, check out my Medium article.

NOTE: USE THE SHA-1 GENERATED FROM YOUR SYSTEM

Step 3: Completing the iOS integration

For the iOS part, you have to do one more step. You will find a TODO in Info.plist file, just complete that.

Step 4: Run the app

Now, you can run the app on your device using the command:

flutter run

Screenshots

Plugins

The plugins used in this project are:

  1. firebase_core
  2. firebase_auth.
  3. google_sign_in.

Add this to your package's pubspec.yaml file to use Firebase & Google Sign In:

dependencies:
  firebase_core: ^0.5.0
  firebase_auth: ^0.18.0+1
  google_sign_in: ^4.5.3

Import using:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:google_sign_in/google_sign_in.dart';

Methods

Following are two useful methods for authentication using Firebase and Google Sign In. You can use these as the basic template for your starting project.

NOTE: These does not check for all edge cases and you should add other security restrictions as per your requirement in your production app

For signing in using a Google account:

Future<String> signInWithGoogle() async {
  await Firebase.initializeApp();

  final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  final UserCredential authResult = await _auth.signInWithCredential(credential);
  final User user = authResult.user;

  if (user != null) {
    // Checking if email and name is null
    assert(user.email != null);
    assert(user.displayName != null);
    assert(user.photoURL != null);

    name = user.displayName;
    email = user.email;
    imageUrl = user.photoURL;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final User currentUser = _auth.currentUser;
    assert(user.uid == currentUser.uid);

    print('signInWithGoogle succeeded: $user');

    return '$user';
  }

  return null;
}

For signing out of a Google account:

Future<void> signOutGoogle() async {
  await googleSignIn.signOut();

  print("User Signed Out");
}

License

Copyright (c) 2019 Souvik Biswas

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • signInWithGoogle().whenComplete is triggered whether or not the login succeeds

    signInWithGoogle().whenComplete is triggered whether or not the login succeeds

    which seems to be the expected behaviour of whenComplete:

    "Registers a function to be called when this future completes. The [action] function is called when this future completes, whether it does so with a value or with an error."

    changing the signInWithGoogle() to return the user and then rewriting as follows seems to do the trick:

            signInWithGoogle().then((user) {
              if (user != null) {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) {
                      return [...]();
                    },
                  ),
                );
              }
    
    
    opened by pgainullin 7
  •  Failed assertion: line 22 pos 14: 'url != null': is not true.

    Failed assertion: line 22 pos 14: 'url != null': is not true.

    help i have this error ...

    ════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ The following assertion was thrown building FirstScreen(dirty): 'package:flutter/src/painting/_network_image_io.dart': Failed assertion: line 22 pos 14: 'url != null': is not true.

    opened by daniele777 3
  • Add network connectivity check

    Add network connectivity check

    Objectives

    • Add a network connectivity check before showing the Login Screen.
    • Add a new screen, which will show when there is no network connection.

    Follow these steps for contributing:

    1. Fork this repo.
    2. Clone it to your local system.
    3. Add new files or modify files by creating a new branch named "network_check".
    4. Then commit and push it.
    5. Now, create a Pull Request.

    NOTE: Please create a new branch before start working, from the master branch. Otherwise, your PR will be rejected.

    ‣ You are free to add animations (Flare animations are preferred) & illustrations. You are free to show as much UI design creativity as you want.

    ‣ You should also add comments wherever necessary.

    enhancement hacktoberfest 
    opened by sbis04 3
  • Null User After Account Select on Android

    Null User After Account Select on Android

    I am experiencing a weird issue on Android Devices.

    When Android users open the app (I created a build and sent them the APK, not via Play store), and click the Sign In button they are presented with a list of accounts they are currently signed into, this includes their G Suite Domain Account and potentially personal accounts.

    image Note: First account is personal Gmail second account is a domain account.

    When selecting the domain account, the user passes authentication and lands at the designated home screen where it should display the users first name, when this bug is experienced the first name returns Null.

    image

    SizedBox(height: 10),
                      Padding(
                        padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                        child: Text(
                          "G'Day $firstName",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.black,
                              fontStyle: FontStyle.normal,
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      ),
    

    It would appear at this stage the user is actually not Authenticated but IS able to use the app as normal.

    Secondly, the API should be scoped for internal use only to our domain, but does allow any Google user to authenticate, resulting in the same issue as above.

    I can not reproduce this issue on iOS Devices, only Android and largely Android 10.

    opened by jeremyw24 2
  • Firebase Auth doesnt work

    Firebase Auth doesnt work

    Running "flutter pub get" in xyz Screenshot from 2020-07-15 21-20-59

    The current Flutter SDK version is 1.12.13.

    Because flutter_simple_slider depends on firebase_auth >=0.15.2 which requires Flutter SDK version >=1.12.13+hotfix.4 <2.0.0, version solving failed. pub get failed (1; Because flutter_simple_slider depends on firebase_auth >=0.15.2 which requires Flutter SDK version >=1.12.13+hotfix.4 <2.0.0, version solving failed.) Process finished with exit code 1

    opened by sohailg 2
  • FirebaseCore/Sources/Private/FirebaseCoreInternal.h  file not found

    FirebaseCore/Sources/Private/FirebaseCoreInternal.h file not found

    hi @sbis04 when i run the project for ios i get this error, the flutter doctor is ok

    can you give me some suggestions, thanks in advance

    sign_in_flutter-master/ios/Pods/FirebaseAuth/FirebaseAuth/Sources/User/FIRUser.m:20:9: fatal error: 'FirebaseCore/Sources/Private/FirebaseCoreInternal.h' file not found #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated.

    opened by lizhaobomb 2
  • LoginScreen() splashes on reopening the app.

    LoginScreen() splashes on reopening the app.

    Maybe it takes the app for a while to know the state or what. But whenever the app is reopened the LoginScreen() splashes for a second then redirects to FirstScreen() if the user is logged in.

    opened by udaykhalsa 2
  • Exception after logging in due to no Firebase App

    Exception after logging in due to no Firebase App

    I have followed the instructions on https://blog.codemagic.io/firebase-authentication-google-sign-in-using-flutter/, but had to update some of the authentication methods as it appears the latest version of the Firebase Auth SDK doesn't have AuthResult.

    After signing in via Google, I get the following exception:

    Exception has occurred.
    FirebaseException ([core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp())
    

    I have since added the firebase_core dependency and call Firebase.app() but the same error occurs.

    final FirebaseApp app = Firebase.app();
    final FirebaseAuth _auth = FirebaseAuth.instance;
    

    Any help on this would be appreciated.

    opened by ricsantos 1
  • [Enhancement] Network check

    [Enhancement] Network check

    • Added a scale transition class to handle transition animations between pages
    • Added icon and text for a no network page when there is no connection
    • Added connectivity library to check for connections and handle page transitions accordingly

    Attached issue https://github.com/sbis04/sign_in_flutter/issues/2

    opened by march93 1
  • [Feature] Added golden tests

    [Feature] Added golden tests

    Added Golden tests for the issue: Fixes #3

    I recommend you 100% to use Flutter Golden tests for widget testing If it is possible. Are like a snapshot test.

    Also, I have added some null checks on the first_screen because it can make it crash.

    I recommend you to refactor the project to BLoC Architecture with Providers to separate clearly all the layers (Data, Logic, UI)

    If you need more help just tell me 😄

    opened by davidfranquet 1
Owner
Souvik Biswas
Android, iOS & Flutter Developer | C++, Java and Dart Programmer | Technical Writer @Medium & @codemagic-ci-cd | @udacity Secure and Private AI '19 Scholar
Souvik Biswas
Find The Latest trending and upcoming movies and tv shows with MovieDB app. The app contains all info about movies and tv shows. find similar movies or shows, Browse all genres, video trailers, backdrops, logos, and posters.

MovieDB App Features. Dynamic Theming Search Functionality Onboarding-Screen Select favourite movie Home Screen Tranding movie Movies different catego

Ansh rathod 80 Dec 12, 2022
A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision.

Smart Notes A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision. This is an official entry to Fl

Cross Solutions 88 Oct 26, 2022
Simple face recognition authentication (Sign up + Sign in) written in Flutter using Tensorflow Lite and Firebase ML vision library.

FaceNetAuthentication Simple face recognition authentication (Sign up + Sign in) written in Flutter using Tensorflow Lite and Google ML Kit library. S

Marcos Carlomagno 279 Jan 9, 2023
6.SignIn SignUp-UI - SIGN IN And SIGN UP UI For Flutter

SIGN IN & SIGN UP UI Text Fields Box Shadow Gradient resizeToAvoidBottomInset Ri

Tukhtamurodov Sardorbek 3 May 16, 2022
Responsive Scaffold - On mobile it shows a list and pushes to details and on tablet it shows the List and the selected item. Maintainer: @rodydavis

responsive_scaffold View the online demo here! On mobile it shows a list and pushes to details and on tablet it shows the List and the selected item.

Flutter Community 346 Dec 2, 2022
This is a Flutter app which shows how to use the PageView Class in your Flutter App

page_view_class A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Shehzaan Mansuri 1 Oct 25, 2021
This is a Flutter app which shows how to use the Selectable Text in your app

selectable_text A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Shehzaan Mansuri 1 Oct 25, 2021
Flutter package implements Sign Google redirect(working for incognito mode)

google_sign_in_web_redirect Flutter package implements Sign Google redirect(working for incognito mode). Usage Import the package dependencies: goog

null 2 Dec 15, 2022
A google browser clone which is made by using flutter and fetching the google search api for the search requests.

google_clone A new Flutter project. Project Preview Getting Started This project is a starting point for a Flutter application. A few resources to get

Priyam Soni 2 May 31, 2022
A Demo application📱 which stores User feedback from 💙Flutter application into Google Sheets🗎 using Google AppScript.

?? Flutter ?? to Google Sheets ?? A Demo application which stores User feedback from Flutter application into Google Sheets using Google AppScript. Yo

Shreyas Patil 289 Dec 28, 2022
A widget that shows an image which can be scaled and dragged using gestures.

[DISCONTINUED] - 24.05.2021 While this widget was useful in the early days of Flutter, the Flutter team introduced an own way to zoom and pan, see Int

EPNW 15 May 3, 2022
This is a Flutter app which shows how to add a Fitted Box in you App

fittedbox A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Shehzaan Mansuri 1 Oct 25, 2021
WooCommerce App template that uses Flutter. Integrated to work with WooCommerce stores, connect and create an IOS and Android app from Flutter for IOS and Android

WooCommerce App: Label StoreMax Label StoreMax - v5.3.1 Official WooSignal WooCommerce App About Label StoreMax Label StoreMax is an App Template for

WooSignal 314 Jan 9, 2023
Flutter App Build for the machine Learning model which shows sentiments of instagram user by analysing their captions

InstaKnow Front-end By @ketanchoyal Back-end By @namas191297 Front-end Application Flutter application that allows user to analyze sentiments of other

Ketan Choyal 40 Oct 28, 2022
This is a Flutter Food Recipe App this shows food recipes of any food which you want.

food_recipe_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Saksham gupta 3 Oct 31, 2022
Source code for login demo in Coding with Flutter series

Flutter & Firebase Authentication demo Source code based on my Flutter & Firebase Authentication video series: Part 1 Part 2 Part 3 Part 4 Part 5 Part

Andrea Bizzotto 162 Dec 29, 2022
This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two pages application with user bid in input and count down view.

Nilam This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two

Md. Siam 5 Nov 9, 2022