Created
November 3, 2020 09:15
FirebaseAuthentication demo using Google Sign-in in Flutter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:firebase_auth/firebase_auth.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_signin_button/button_view.dart'; | |
import 'package:flutter_signin_button/flutter_signin_button.dart'; | |
import 'package:google_sign_in/google_sign_in.dart'; | |
class SignInDemoApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Google Sign-In Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.deepOrange, | |
), | |
home: SignInDemo(), | |
); | |
} | |
} | |
class SignInDemo extends StatefulWidget { | |
@override | |
State createState() => SignInDemoState(); | |
} | |
class SignInDemoState extends State<SignInDemo> { | |
final _auth = FirebaseAuth.instance; | |
@override | |
void initState() { | |
super.initState(); | |
_auth.authStateChanges().listen((User user) { | |
if (user == null) { | |
print('User is currently signed out!'); | |
} else { | |
print('User is signed in!'); | |
} | |
}); | |
} | |
// Googleを使ってサインイン | |
Future<UserCredential> signInWithGoogle() async { | |
// 認証フローのトリガー | |
final googleUser = await GoogleSignIn(scopes: [ | |
'email', | |
]).signIn(); | |
// リクエストから、認証情報を取得 | |
final googleAuth = await googleUser.authentication; | |
// クレデンシャルを新しく作成 | |
final credential = GoogleAuthProvider.credential( | |
accessToken: googleAuth.accessToken, | |
idToken: googleAuth.idToken, | |
); | |
// サインインしたら、UserCredentialを返す | |
return FirebaseAuth.instance.signInWithCredential(credential); | |
} | |
@override | |
Widget build(BuildContext context) { | |
FirebaseAuth.instance.authStateChanges().listen((User user) { | |
if (user == null) { | |
print('User is currently signed out!'); | |
} else { | |
print('User is signed in!'); | |
} | |
}); | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text( | |
'Google Sign-In Demo', | |
), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
SignInButton( | |
Buttons.Google, | |
onPressed: () async { | |
try { | |
final userCredential = await signInWithGoogle(); | |
} on FirebaseAuthException catch (e) { | |
print('FirebaseAuthException'); | |
print('${e.code}'); | |
} on Exception catch (e) { | |
print('Exception'); | |
print('${e.toString()}'); | |
} | |
}, | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment