Skip to content

Commit cd5f0af

Browse files
authored
Create streamprovider-in-flutter-riverpod.dart
1 parent 90be1ad commit cd5f0af

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// 🐦 Twitter https://twitter.com/vandadnp
2+
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
3+
// 🎥 YouTube https://youtube.com/c/vandadnp
4+
// 💙 Free Flutter Course https://linktr.ee/vandadnp
5+
// 📦 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY
6+
// 🔶 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI
7+
// 🦄 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro
8+
// 🤝 Want to support my work? https://buymeacoffee.com/vandad
9+
10+
import 'dart:async';
11+
import 'package:cloud_firestore/cloud_firestore.dart';
12+
import 'package:hooks_riverpod/hooks_riverpod.dart';
13+
14+
final userPostsProvider = StreamProvider.family<Iterable<Post>, UserID?>((
15+
ref,
16+
UserID? userId,
17+
) {
18+
19+
if (userId == null) {
20+
return const Stream<Iterable<Post>>.empty();
21+
}
22+
23+
final controller = StreamController<Iterable<Post>>();
24+
25+
final subscription = FirebaseFirestore.instance
26+
.collection('posts')
27+
.where(PostKey.userId.key, isEqualTo: userId)
28+
.snapshots()
29+
.listen(
30+
(snapshot) {
31+
final documents = snapshot.docs;
32+
final posts = documents.map(
33+
(doc) => Post.fromJson(
34+
doc.data(),
35+
),
36+
);
37+
controller.sink.add(posts);
38+
},
39+
);
40+
41+
ref.onDispose(() {
42+
subscription.cancel();
43+
controller.close();
44+
});
45+
46+
return controller.stream;
47+
});

0 commit comments

Comments
 (0)