Google Authentication in flutter (firebase)

              In this article, I will show how to set up a Flutter app and implement Google Sign-In using Firebase authentication.




Come, today we learn to sign in from Google, so first of all we have complete setup of Firebase, read from there in the blog.

After that enable google authentication in firebase console



After this, the library has to be imported in your project


dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_auth: ^4.1.2
firebase_core: ^2.2.0
google_sign_in: ^5.4.2
flutter_signin_button: ^2.0.0

Do all this code in your main file


import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_list.dart';
import 'package:flutter_signin_button/button_view.dart';
import 'package:flutterfirebasedemo/HomePage.dart';
import 'package:google_sign_in/google_sign_in.dart';

Future<void> main() async {

WidgetsFlutterBinding.ensureInitialized();

// initializing the firebase app
await Firebase.initializeApp();
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(
title: 'Flutter Demo',
theme: ThemeData(

primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});



final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

final FirebaseAuth auth = FirebaseAuth.instance;

void _incrementCounter() {
setState(() {

_counter++;
});
}


googleSignInMethod() async {
//_showDialog(true);
GoogleSignInAccount? googleSignInAccount = await GoogleSignIn().signIn();
try {
GoogleSignInAuthentication googleAuth =
await googleSignInAccount!.authentication;

GoogleAuthCredential? credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken) as GoogleAuthCredential?;

UserCredential signedInCredentials =
await auth.signInWithCredential(credential!);
User? tempUser = signedInCredentials.user;
/*_sessionManager.saveString(Constants.User_ID, tempUser!.uid);*/
print("Name : " + tempUser!.displayName.toString());
print("Email : " + tempUser.email.toString());
print("PhotoUrl : " + tempUser.photoURL.toString());
print("User Details : " + tempUser.toString());

if (tempUser != null) {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomePage()));
} // if result not null we simply call the MaterialpageRoute,
// for go to the HomePage screen

// ScaffoldMessenger.of(context)
// .showSnackBar(SnackBar(content: Text('Login Successfully')));
} catch (e) {
// _showDialog(false);
print("Error Message : " + e.toString());
}
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(

mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
SignInButton(
Buttons.Google,
text: "Sign up with Google",
onPressed: () {
print("google");
googleSignInMethod();
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}



I hope you enjoy my article read. please share with your friends. thank you!

Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

HTTP GET Response in Flutter

Building a Flutter Firebase Firestore CRUD App