Flutter plugin for Google Sign-In and Firebase settings in IOS system
firebase新增專案
在firebase新增專案
建立專案
如果沒有要使用GA分析的話,可以先不要點選
點選ios應用
將firebase新增到ios應用
Enter ios bundle ID and App nickname
ios bundle(IOS軟體包)可以flutter專案中的ios資料夾ios/Runner.xcodeproj/project.pbxproj中找到
PRODUCT_BUNDLE_IDENTIFIER
下載設定檔
在mac打開xcode
將下載下來的GoogleService-Info放到runner裡面,點選finish
設定/ios/Runner/Info.plist
複製flutter google_sigin_in package 中Readme ios integration第七點
複製到/ios/Runner/Info.plist
到下載下來的GoogleService-Info複製REVERSED_CLIENT_ID
修改/ios/Runner/Info.plist內的REVERSED_CLIENT_ID
新增firebase SDK
這個步驟可以不用修改任何資料,我們使用flutter套件來設定
新增初始化程式碼
這個步驟可以不用修改任何資料,我們使用flutter套件來設定
進到Authentication
啟用google
點選google,並在專案支援電子郵件輸入管理的E-mail
設定Flutter專案
在pubspec.yaml新增以下套件
執行flutter pub get
新增asset資料夾
新增asset資料夾,並在pubspec.yaml設定asset路徑
下載google logo命名為google_logo.png放到asset資料夾
修改main.dart ui
import 'package:flutter/material.dart';import 'login_page.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Login',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(),
);
}
}
新增login_page.dart在lib資料夾
import 'package:flutter/material.dart';import 'sign_in.dart';class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}class _LoginPageState extends State<LoginPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.white,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlutterLogo(size: 150),
SizedBox(height: 50),
_signInButton(),
],
),
),
),
);
} Widget _signInButton() {
return OutlineButton(
splashColor: Colors.grey,
onPressed: () {
signInWithGoogle().then((result) {
if (result != null) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return FirstScreen();
},
),
);
}
});
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
highlightElevation: 0,
borderSide: BorderSide(color: Colors.grey),
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network('https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Google_Chrome_icon_%282011%29.svg/512px-Google_Chrome_icon_%282011%29.svg.png', height: 35.0),
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
'Sign in with Google',
style: TextStyle(
fontSize: 20,
color: Colors.grey,
),
),
)
],
),
),
);
}
}class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.blue[100], Colors.blue[400]],
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(
imageUrl,
),
radius: 60,
backgroundColor: Colors.transparent,
),
SizedBox(height: 40),
Text(
'NAME',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
Text(
name,
style: TextStyle(
fontSize: 25,
color: Colors.deepPurple,
fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Text(
'EMAIL',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
Text(
email,
style: TextStyle(
fontSize: 25,
color: Colors.deepPurple,
fontWeight: FontWeight.bold),
),
SizedBox(height: 40),
RaisedButton(
onPressed: () {
signOutGoogle();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {return LoginPage();}), ModalRoute.withName('/'));
},
color: Colors.deepPurple,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Sign Out',
style: TextStyle(fontSize: 25, color: Colors.white),
),
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40)),
)
],
),
),
),
);
}
}
新增sign_in.dart在lib資料夾
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:google_sign_in/google_sign_in.dart';final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();String name;
String email;
String imageUrl;Future<String> signInWithGoogle() async {
await Firebase.initializeApp(); final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
); final UserCredential authResult = await _auth.signInWithCredential(credential);
final User user = authResult.user; if (user != null) {
assert(!user.isAnonymous);
assert(await user.getIdToken() != null); // Add the following lines after getting the user
// Checking if email and name is null
assert(user.email != null);
assert(user.displayName != null);
assert(user.photoURL != null); // Store the retrieved data
name = user.displayName;
email = user.email;
imageUrl = user.photoURL; // Only taking the first part of the name, i.e., First Name
if (name.contains(" ")) {
name = name.substring(0, name.indexOf(" "));
} final User currentUser = _auth.currentUser;
assert(user.uid == currentUser.uid); print('signInWithGoogle succeeded: $user'); return '$user';
} return null;
}Future<void> signOutGoogle() async {
await googleSignIn.signOut(); print("User Signed Out");
}
DEMO
登入畫面
點選按鈕導到google登入頁面
登入成功畫面
顯示使用者照片、帳號名稱和E-mail
登入成功回傳資料
其中uid可以存下來註冊在App的資料庫中,作為使用者註冊App的ID
參考資料:
Add Firebase to your Flutter app
pub.dev:google_sign_in
https://pub.dev/packages/google_sign_in
Google sign-in & Firebase authentication using Flutter
https://blog.codemagic.io/firebase-authentication-google-sign-in-using-flutter/