flutter sign in google

There are so many apps will provide options sign in to the apps, such as sign in or sign up with google, sign in with facebook and so on. In this article we will learn how to implement sign in ofr sign up with google or other social media using firebase in flutter.

Table of Contents

Introduction

Every time you join to new apps or website you should to register before you using it. Meanwhile, you have to fill in the register form to complete the registration, basically every form registration have a common data to fill, start from username, full name, date of birthday, password and gender. Yups, those basic data to fill. In order to make it sample, many apps will provide some option for sign up with some social media account to automatic fill those fields.

For that reason, here we will try to make a sign in or sign up our apps with social media account like google, facebook and so on.

Google Sign In

Common apps will implement with this option, Google Sign In. Google account store our profile information that we can setting to showing some data to public like name, email address, phone number, etc. Implementing Google Sign In to our apps is really easy, so please be careful to follow step by step here.

To get this option we will use plugin:

  1. firebase_auth (Firebase Authentication)
  2. google_sign_in (Implementation of Google Sign In)

Let’s get started…!!!

To start this project, make sure you already upgrade your flutter sdk and switch to channel stable. Type this command to check you are currently on.

flutter channel

The mark (*) asterisk is indicating that where you branch now, if you are not in branch stable, you need to switch.

 flutter channel stable

Then upgrade your fluuter by this command.

flutter upgrade

Finally you are ready to create project. Navigate to folder that you want to create project, and type here in terminal.

 flutter create --androidx ui_online_chat 

Once your project is ready, let’s open file and add this package plugin

firebase_auth: ^0.16.1  
google_sign_in: ^4.5.1 
flutter google sign in package

Save your file and wait till project download those package. Afterward, modify file main.dart for login page and put this code.

Main.dart
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'dart:convert' show json;
import "package:http/http.dart" as http;

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);
class _MyHomePageState extends State<MyHomePage> {
  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: GoogleUserCircleAvatar(
              identity: _currentUser,
            ),
            title: Text(_currentUser.displayName ?? ''),
            subtitle: Text(_currentUser.email ?? ''),
          ),
          const Text("Signed in successfully."),
          Text(_contactText ?? ''),
          RaisedButton(
            child: const Text('SIGN OUT'),
            onPressed: _handleSignOut,
          ),
          RaisedButton(
            child: const Text('REFRESH'),
            onPressed: _handleGetContact,
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in."),
          RaisedButton(
            child: const Text('SIGN IN'),
            onPressed: _handleSignIn,
          ),
        ],
      );
    }
  }

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

You already setup UI in your app, next step is, you need to create project in firebase. Go to firebase site, click Get Started.

Firebase Setting

flutter sign in google - firebase get started

Login to firebase with your google account, then click Add Project.

flutter sign in google - firebase add project

Type your project name, and click Continue

flutter sign in google - firebase create project name

There are 2 step left you need to follow, just click Continue

flutter sign in google - firebase add project

flutter sign in google - firebase add project

Here you need to select your account and click Add Firebase

flutter sign in google - firebase add project

Wait a moment until process creating project, once it done, click Continue.

flutter sign in google - firebase add project

Android Setting

Now you will go to dashboard firebase, and let’s configure android project by clicking android icon.

flutter sign in google - firebase dashboard

You will go to new window to setting your android project, on the step one, you need to complete form android package.

flutter sign in google - firebase add project

Type your android package as you want, but if you feel confuse about the name, you can take default name of your flutter project in Manifest file in root folder android\app\src\main\AndroidManifest.xml.

flutter sign in google - manifest file

Please notice that if you type your android package name is different as package name in manifest file, so you need change your package name in manifest file with package name in firebase project.

Next, in field of certificate SHA-1, you need to get your certificate android project. To get your certificate, just hover your cursor to question symbol and click See this page, then you will bring to new tab on how to get certificate. Click on tab Mac/Linux if you use OS Mac or Linux, but here i’m use Windows.

flutter sign in google - get certificate SHA-1

Copy that script and paste in your project terminal, remove backslash and make it just inline then enter, and there will be keystore password, just press enter and you will see certificate SHA1.

flutter sign in google - get certificate SHA-1

Copy value SHA1 and paste to firebase project, then click Register app

flutter sign in google - firebase add SHA-1

In step 2 you need to download file google-services.json, it contain authentication to your firebase project, and copy that file to root folder android\app\google-services.json.

flutter sign in google - firebase downloadn google-service.json

After you copy file to your project, click Next to jump to step 3, in there you will see configuration. You need to add that to your flutter project.

flutter sign in google - firebase configuration

The instruction is very clear, there are two gradle file you need to modify. First, open file build.gradle in path android\build.gradle, copy code here into dependencies section.

 classpath 'com.google.gms:google-services:4.3.3' 

flutter sign in google - gradle

And the last, open build.gradle in path \android\app\build.gradle, copy code to this section.

flutter sign in google - gradle

Once you done modify those file, let’s go back to your firebase project and click Next. In step 4, you need to running you flutter project to verify that your configuration have been detected by firebase.

flutter sign in google - firebase verify installation project

Once you running your flutter project and firebase will detect your configuration, then step 4 will notify that you’ve successfully. Click Continue to console to go to firebase console.

flutter sign in google - success add firebase to your app

You already add new firebase project, so now the last step in firebase configuration is we need to enable authentication. In dashboard menu, click Authentication and click Sign-In method,

flutter sign in google - Firebase authentication menu

On the right panel, you will see there are several Sign-In providers that you can choose for your authentication, now we just click on Google and there is popup setting, switch to Enable and click Save.

flutter sign in google - firebase google authentication

Oke, every configuration that we need in firebase already done, but you cannot running your project, yet. There is another configuration in your flutter project that you need to make sure, so lets go to flutter project, go to path folder \android\app\src\main\java\.

flutter flutter sign in google - mainactivity.java

if you don’t have file MainActivity.java in there, you need to create that file and put this code.

MainActivity.java

package com.example.ui_online_chat;

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
  }
}

And the last step that you need to do is, check on your file AndroidManifest.xml, if this code exist there. Please comment or delete it.

flutter sign in google

Make a comment like this.

flutter sign in google - remove meta manifest file

So now, you are ready to running your project. Lets run your project and the result should be like this.

flutter sign in google

Hope this useful for you.

You can get full source code on my github here.

HAPPY SHARE!!!

Advertisements
Share: