昨天的文章30天Flutter手滑系列 - 聊天室開發(Chat Room)(8),我們建好了基本的聊天室介面,今天要來重新把Firebase和APP起來。
我把Firebase
的專案刪掉重建了一番,然後專案內的檔案也重新整理了。
單獨把登入相關的功能放到login.dart
,並且參考firebase_auth
,在按鈕的onPressed
加入例外處理,去攔截相關錯誤。
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class LoginPage extends StatefulWidget {
@override
LoginPageState createState() {
return new LoginPageState();
}
}
class LoginPageState extends State<LoginPage> {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> _handleSignIn() async {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final FirebaseUser user =
(await _auth.signInWithCredential(credential)).user;
print("signed in " + user.displayName);
return user;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login Page'),
),
body: Container(
child: RaisedButton(
child: Text('Sign in'),
onPressed: () {
_handleSignIn()
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
},
),
),
);
}
}
以上更進階用法,可以參考firebase_auth