Open In App

Google Sign In With Firebase in Flutter Web

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. Google Sign-in with Firebase in the Flutter Web app can be done by choosing the account through which you wish to sign in.

Step by Step Implementation

Step 1: Create a new Flutter app in Android Studio

Open Android Studio -> Go to New Flutter Project -> Select Flutter in the left tab and Flutter SDK Path and go to Next. Specify the project name, project location, and project type as Application, and select Web also in the Platforms section. Click on Finish. You can see a directory named Web is now created along with all the directories.

Step 2: Create a web app in Firebase

Create a Firebase project in the Firebase Console. In Project Overview, go to Web.

 

Set a web app name -> Click on Register App. In the Add Firebase SDK section, copy the following code.

 

Step 3:

Create a GoogleSignIn.dart file in the lib directory and refer to the following code.

Dart




import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
  
class GoogleSignIn extends StatefulWidget {
  const GoogleSignIn({Key? key}) : super(key: key);
  
  @override
  State<GoogleSignIn> createState() => _GoogleSignInState();
}
  
class _GoogleSignInState extends State<GoogleSignIn> {
  final GoogleSignIn googleSignIn = GoogleSignIn();
  String? name, imageUrl, userEmail, uid;
  
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
  
    return Scaffold(
      body: Container(
        height: size.height,
        width: size.width,
        child: Center(
          child: InkWell(
            onTap: (){
              signInWithGoogle();
  
            },
            child: Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
                borderRadius: BorderRadius.circular(10)
              ),
              child: Text('Sign In with Google'),
            ),
          ),
        ),
      ),
    );
  }
  Future<User?> signInWithGoogle() async {
    // Initialize Firebase
    await Firebase.initializeApp();
    User? user;
    FirebaseAuth auth = FirebaseAuth.instance;
    // The `GoogleAuthProvider` can only be 
    // used while running on the web
    GoogleAuthProvider authProvider = GoogleAuthProvider();
  
    try {
      final UserCredential userCredential =
      await auth.signInWithPopup(authProvider);
      user = userCredential.user;
    } catch (e) {
      print(e);
    }
  
    if (user != null) {
      uid = user.uid;
      name = user.displayName;
      userEmail = user.email;
      imageUrl = user.photoURL;
  
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setBool('auth', true);
      print("name: $name");
      print("userEmail: $userEmail");
      print("imageUrl: $imageUrl");
    }
    return user;
  }
}


Step 4:

Go to the index.html file in the web directory and write the following code inside the body tag. As we are working with the web, we only need to make changes in the index.html. We don’t need to download the google-services.json file.

HTML




  
  <script>
    // paste the code copied 
    // from Firebase SDK below.
    const firebaseConfig = {
      apiKey: "",
      authDomain: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: "",
      appId: "",
      measurementId: ""
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
      
  </script>


Step 5:

Go to main.dart file in lib and initialize Firebase in the main file.

Dart




import 'package:authe/googleSignIn.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
  
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      options: const FirebaseOptions(
             // these are variable 
          // for each firebase project
          apiKey: "",
          authDomain: "",
          projectId: "",
          storageBucket: "",
          messagingSenderId: "",
          appId: "",
          measurementId: "")
  );
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GoogleSignIn(),
    );
  }
}


Step 6:

Select a device as Chrome (web) or Edge (web) as per your choice. Then Run the application. Click on the ‘Sign In with Google’ button and choose your account.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads