如何将Future转换为Flutter中的流,其中数据实时更新



我有一个Future方法(getUserProfileData),我使用它来检索用户帖子的数量、关注者的数量、userName、profileImage等。对于数据的一次性检索,它可以完美地工作。如果用户添加了一个帖子,我希望UI上的帖子数量能够实时更新,而不必导航到一个新页面并返回刷新UI。我已经审查了不同的SO线程,阅读文档和Firestore工作完美。问题是,我有限的经验水平使我很难弄清楚如何重构代码以获得我想要的行为。我已经删除了填充,容器和其他布局代码,以缩短提交的代码。如有任何帮助,不胜感激。

class ProfileTabExample extends StatefulWidget {
const ProfileTabExample({
Key? key,
required this.profileID,
required this.userProfileKey,
}) : super(key: key);
final String profileID;
final Key userProfileKey;
@override
State<ProfileTabExample> createState() => _ProfileTabExampleState();
}
class _ProfileTabExampleState extends State<ProfileTabExample> {
Map<String, dynamic> userData = {};
int postLength = 0;
int followers = 0;
int following = 0;
bool isFollowing = false;
bool isLoading = false;
final String currentUser = Auth().currentUser?.uid as String;
@override
void initState() {
super.initState();
_getUserProfileData();
}
Future _getUserProfileData() async {
setState(() {
isLoading = true;
});
try {
DocumentSnapshot<Map<String, dynamic>> userSnap = await FirebaseFirestore
.instance
.collection('users')
.doc(widget.profileID)
.get();
QuerySnapshot<Map<String, dynamic>> postSnap = await FirebaseFirestore
.instance
.collection('posts')
.where('userID', isEqualTo: Auth().currentUser?.uid)
.get();
postLength = postSnap.docs.length;
userData = userSnap.data() as Map<String, dynamic>;
followers = userData['followers'].length;
following = userData['following'].length;
isFollowing = userData['followers'].contains(Auth().currentUser?.uid);
setState(() {});
} catch (e) {
SnackBarUtil.showSnackBar(
context,
e.toString(),
);
}
setState(() {
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return isLoading
? const AdaptiveCircularProgress()
: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
ProfileStatColumn(
count: postLength,
label: ProfilePageString.posts,
),
ProfileStatColumn(
count: followers,
label: ProfilePageString.followers,
),
ProfileStatColumn(
count: following,
label: ProfilePageString.following,
),
],
),
),
],
);
}
}

snapshots方法提供stream,它通知更改。使用StreamBuilder重建一个小部件。

像这样:

StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('posts').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
...
},
);

最新更新