Last active
March 1, 2023 22:35
-
-
Save mono0926/73f258fd734c799bb6df8e19109c7f66 to your computer and use it in GitHub Desktop.
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:cloud_firestore/cloud_firestore.dart'; | |
import 'package:firebase_auth/firebase_auth.dart'; | |
import 'package:riverpod/riverpod.dart'; | |
// 1つ目のStreamProvider | |
final authUserProvider = | |
StreamProvider<User?>((ref) => FirebaseAuth.instance.userChanges()); | |
// 2つ目のStreamProvider | |
// authUserProviderをwatchした値を使ってFirestoreから得られるStreamを返す | |
final userSnapshotProvider = StreamProvider((ref) async* { | |
final uid = | |
await ref.watch(authUserProvider.selectAsync((user) => user?.uid)); | |
if (uid == null) { | |
// 値を返す時は`yield`を使う | |
yield null; | |
return; | |
} | |
// Streamを返すときは`yield*`を使う | |
// (実際には`.withConverter`挟むのが良い) | |
yield* FirebaseFirestore.instance.collection('users').doc(uid).snapshots(); | |
}); | |
// こういう時はFutureProviderで済む | |
// (元のコード例では不自然にStreamProviderになっていた) | |
final isSignedInProvider = FutureProvider<bool>((ref) async { | |
final user = await ref.watch(authUserProvider.future); | |
return user != null; | |
}); | |
// 別解 | |
final isSignedInProvider2 = FutureProvider<bool>( | |
(ref) => ref.watch(authUserProvider.selectAsync((user) => user != null)), | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment