Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save welchi/f38e87ee40792f2cd686f3ba55528c49 to your computer and use it in GitHub Desktop.
Save welchi/f38e87ee40792f2cd686f3ba55528c49 to your computer and use it in GitHub Desktop.
FirebaseAuthentication demo using Google Sign-in in Flutter.
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