Skip to content

Commit

Permalink
Adapt to latest firebase APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
X-Wei committed Sep 27, 2020
1 parent 817fde8 commit d09f2fe
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 38 deletions.
14 changes: 5 additions & 9 deletions lib/routes/firebase_chatroom_ex.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
Expand All @@ -18,7 +18,7 @@ class FirebaseChatroomExample extends StatefulWidget {
}

class _FirebaseChatroomExampleState extends State<FirebaseChatroomExample> {
FirebaseUser _user;
firebase_auth.User _user;
DatabaseReference _firebaseMsgDbRef;

final TextEditingController _textController = TextEditingController();
Expand All @@ -31,11 +31,7 @@ class _FirebaseChatroomExampleState extends State<FirebaseChatroomExample> {
this._firebaseMsgDbRef = FirebaseDatabase.instance
.reference()
.child('messages/${now.year}/${now.month}/${now.day}');
FirebaseAuth.instance.currentUser().then(
(user) => setState(() {
this._user = user;
}),
);
this._user = firebase_auth.FirebaseAuth.instance.currentUser;
}

@override
Expand Down Expand Up @@ -190,7 +186,7 @@ class _FirebaseChatroomExampleState extends State<FirebaseChatroomExample> {
Future<Null> _onTextMsgSubmitted(String text) async {
// Make sure _user is not null.
if (this._user == null) {
this._user = await FirebaseAuth.instance.currentUser();
this._user = firebase_auth.FirebaseAuth.instance.currentUser;
}
if (this._user == null) {
showDialog(
Expand Down Expand Up @@ -219,7 +215,7 @@ class _FirebaseChatroomExampleState extends State<FirebaseChatroomExample> {
_firebaseMsgDbRef.push().set({
'senderId': this._user.uid,
'senderName': this._user.displayName,
'senderPhotoUrl': this._user.photoUrl,
'senderPhotoUrl': this._user.photoURL,
'text': text,
'timestamp': DateTime.now().millisecondsSinceEpoch,
});
Expand Down
49 changes: 25 additions & 24 deletions lib/routes/firebase_login_ex.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'dart:async';
Expand All @@ -17,17 +17,20 @@ class FirebaseLoginExample extends StatefulWidget {
}

class _FirebaseLoginExampleState extends State<FirebaseLoginExample> {
FirebaseUser _user;
final _auth = firebase_auth.FirebaseAuth.instance;
firebase_auth.User _user;
// If this._busy=true, the buttons are not clickable. This is to avoid
// clicking buttons while a previous onTap function is not finished.
bool _busy = false;

@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then(
(user) => setState(() => this._user = user),
);
this._user = _auth.currentUser;
_auth.authStateChanges().listen((firebase_auth.User usr) {
this._user = usr;
debugPrint('user=$_user');
});
}

@override
Expand Down Expand Up @@ -86,60 +89,58 @@ class _FirebaseLoginExampleState extends State<FirebaseLoginExample> {
}

// Sign in with Google.
Future<FirebaseUser> _googleSignIn() async {
final curUser = this._user ?? await FirebaseAuth.instance.currentUser();
Future<firebase_auth.User> _googleSignIn() async {
final curUser = this._user ?? _auth.currentUser;
if (curUser != null && !curUser.isAnonymous) {
return curUser;
}
final googleUser = await GoogleSignIn().signIn();
final googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
final credential = firebase_auth.GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Note: user.providerData[0].photoUrl == googleUser.photoUrl.
final user =
(await FirebaseAuth.instance.signInWithCredential(credential)).user;
final user = (await _auth.signInWithCredential(credential)).user;
kFirebaseAnalytics.logLogin();
setState(() => this._user = user);
return user;
}

// Sign in Anonymously.
Future<FirebaseUser> _anonymousSignIn() async {
final curUser = this._user ?? await FirebaseAuth.instance.currentUser();
Future<firebase_auth.User> _anonymousSignIn() async {
final curUser = this._user ?? _auth.currentUser;
if (curUser != null && curUser.isAnonymous) {
return curUser;
}
FirebaseAuth.instance.signOut();
final anonyUser = (await FirebaseAuth.instance.signInAnonymously()).user;
final userInfo = UserUpdateInfo();
userInfo.displayName = '${anonyUser.uid.substring(0, 5)}_Guest';
await anonyUser.updateProfile(userInfo);
_auth.signOut();
final anonyUser = (await _auth.signInAnonymously()).user;
anonyUser.updateProfile(
displayName: '${anonyUser.uid.substring(0, 5)}_Guest');
await anonyUser.reload();
// Have to re-call `currentUser()` to make `updateProfile` work.
// Cf. https://stackoverflow.com/questions/50986191/flutter-firebase-auth-updateprofile-method-is-not-working.
final user = await FirebaseAuth.instance.currentUser();
final user = _auth.currentUser;
kFirebaseAnalytics.logLogin();
setState(() => this._user = user);
return user;
}

Future<Null> _signOut() async {
final user = await FirebaseAuth.instance.currentUser();
final user = _auth.currentUser;
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(user == null
? 'No user logged in.'
: '"${user.displayName}" logged out.'),
),
);
FirebaseAuth.instance.signOut();
_auth.signOut();
setState(() => this._user = null);
}

// Show user's profile in a new screen.
void _showUserProfilePage(FirebaseUser user) {
void _showUserProfilePage(firebase_auth.User user) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) => Scaffold(
Expand All @@ -151,13 +152,13 @@ class _FirebaseLoginExampleState extends State<FirebaseLoginExample> {
ListTile(title: Text('User id: ${user.uid}')),
ListTile(title: Text('Display name: ${user.displayName}')),
ListTile(title: Text('Anonymous: ${user.isAnonymous}')),
ListTile(title: Text('providerId: ${user.providerId}')),
ListTile(title: Text('providerData: ${user.providerData}')),
ListTile(title: Text('Email: ${user.email}')),
ListTile(
title: Text('Profile photo: '),
trailing: user.photoUrl != null
trailing: user.photoURL != null
? CircleAvatar(
backgroundImage: NetworkImage(user.photoUrl),
backgroundImage: NetworkImage(user.photoURL),
)
: CircleAvatar(
child: Text(user.displayName[0]),
Expand Down
13 changes: 8 additions & 5 deletions lib/routes/firebase_vote_ex.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ class _FirebaseVoteExampleState extends State<FirebaseVoteExample> {
return Center(
child: StreamBuilder<QuerySnapshot>(
// In firestore console I added a "language_voting" collection.
stream: Firestore.instance.collection('language_voting').snapshots(),
stream: FirebaseFirestore.instance
.collection('language_voting')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return LinearProgressIndicator();
} else {
final List<_LangaugeVotingRecord> records = snapshot.data.documents
final List<_LangaugeVotingRecord> records = snapshot.data.docs
.map((snapshot) => _LangaugeVotingRecord.fromSnapshot(snapshot))
.toList()
..sort((record1, record2) => record2.votes - record1.votes);
Expand Down Expand Up @@ -107,15 +109,15 @@ class _FirebaseVoteExampleState extends State<FirebaseVoteExample> {
final lang = record.language;
int deltaVotes = this._isVoted(lang) ? -1 : 1;
// Update votes via transactions are atomic: no race condition.
await Firestore.instance.runTransaction(
await FirebaseFirestore.instance.runTransaction(
(transaction) async {
try {
final freshSnapshot =
await transaction.get(record.firestoreDocReference);
// Get the most fresh record.
final freshRecord =
_LangaugeVotingRecord.fromSnapshot(freshSnapshot);
await transaction.update(record.firestoreDocReference,
transaction.update(record.firestoreDocReference,
{'votes': freshRecord.votes + deltaVotes});
} catch (e) {
throw e;
Expand Down Expand Up @@ -150,7 +152,8 @@ class _LangaugeVotingRecord {
votes = map['votes'];

_LangaugeVotingRecord.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, firestoreDocReference: snapshot.reference);
: this.fromMap(snapshot.data(),
firestoreDocReference: snapshot.reference);

@override
String toString() => "Record<$language:$votes>";
Expand Down

0 comments on commit d09f2fe

Please sign in to comment.