📜  flutter google sign in firebase pub (1)

📅  最后修改于: 2023-12-03 15:00:47.808000             🧑  作者: Mango

Flutter Google Sign In with Firebase

Firebase is a Google-backed mobile development platform that provides a secure and reliable cloud backend for mobile and web applications. Flutter is an open-source mobile app development framework created by Google that enables developers to build high-performance, natively compiled apps for mobile, web, and desktop from a single codebase.

In this tutorial, we will be exploring how to add Google Sign In functionality to a Flutter app using Firebase. We'll be using the following libraries:

  • google_sign_in: Provides sign-in functionality using Google accounts.
  • firebase_auth: Provides authentication and user management services with Firebase.
  • firebase_core: A Flutter plugin to use the Firebase Core API, including configuration and initialization.
Prerequisites

Before beginning this tutorial, you should have the following:

  • A basic understanding of Flutter and Dart.
  • A Google account.
  • A Firebase project set up with a Google Sign-In provider. Follow the Firebase documentation to set up your project.
  • Flutter and Dart installed on your local machine.
Getting Started
Adding Dependencies

To begin, let's add the required dependencies to pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.7.0
  firebase_auth: ^3.3.5
  google_sign_in: ^5.2.1

After adding the dependencies run the flutter pub get command to download the dependencies.

Setting up Firebase in Flutter

To use Firebase in a Flutter app, we first need to initialize it.

To do this, we need to create an instance of Firebase.initializeApp(). We can do this in the main() function of our app:

import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
Creating a Google Sign-In Button

We'll now create a button that will trigger the Google Sign-In process. We'll use the google_sign_in library to handle the actual sign-in process.

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

class LoginScreen extends StatelessWidget {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Sign-In'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _signIn(context),
          child: Text('Sign in with Google'),
        ),
      ),
    );
  }

  void _signIn(BuildContext context) async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Sign in canceled.')));
        return;
      }

      // Use Firebase to authenticate with Google.
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error signing in: $e')));
    }
  }
}
Setting up Firebase Authentication

To authenticate with Firebase, we need to first configure the Firebase app with our Google Sign-In Provider. We can do this by adding the following code to our main() function:

import 'package:firebase_auth/firebase_auth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

  runApp(MyApp());
}
Authenticating with Firebase

We'll now update the _signIn() function to authenticate the user with Firebase after they have signed in with Google.

void _signIn(BuildContext context) async {
  try {
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    if (googleUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Sign in canceled.')));
      return;
    }

    final GoogleSignInAuthentication googleAuth =
        await googleUser.authentication;

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

    await FirebaseAuth.instance.signInWithCredential(credential);

    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Signed in as ${googleUser.displayName}')));
  } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error signing in: $e')));
  }
}
Completing the Login Screen

We're now ready to complete the login screen. We'll display the user's name and profile picture after they've successfully signed in.

class LoginScreen extends StatelessWidget {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: _firebaseAuth.authStateChanges(),
      builder: (BuildContext context, AsyncSnapshot<User?> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        } else if (!snapshot.hasData || snapshot.data == null) {
          return Scaffold(
            appBar: AppBar(
              title: Text('Google Sign-In'),
            ),
            body: Center(
              child: ElevatedButton(
                onPressed: () => _signIn(context),
                child: Text('Sign in with Google'),
              ),
            ),
          );
        } else {
          final user = snapshot.data!;
          return Scaffold(
            appBar: AppBar(title: Text('Welcome, ${user.displayName}!')),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  backgroundImage: NetworkImage(user.photoURL ?? ''),
                  radius: 75,
                ),
                SizedBox(height: 24),
                Text('You are logged in as ${user.email}'),
                SizedBox(height: 24),
                ElevatedButton(
                  onPressed: _signOut,
                  child: Text('Sign Out'),
                )
              ],
            ),
          );
        }
      },
    );
  }

  void _signIn(BuildContext context) async {
    // ...
  }

  void _signOut() async {
    await _firebaseAuth.signOut();
    await _googleSignIn.disconnect();
    await _googleSignIn.signOut();
  }
}
Conclusion

In this tutorial, we learned how to add Google Sign-In functionality to a Flutter app using Firebase. We covered the following topics:

  • Initializing Firebase in a Flutter app
  • Setting up a Google Sign-In button using google_sign_in
  • Authenticating with Firebase using firebase_auth
  • Displaying user profile information after successful sign-in

This is just the beginning of what is possible with Firebase and Flutter. You can customize this example to fit your exact needs, and use the power of Firebase to build powerful, scalable, and reliable mobile and web applications.