【发布时间】:2021-12-05 18:08:13
【问题描述】:
我想获取特定用户喜欢的帖子并在交错网格视图中显示它们。我可以在 FutureBuilder 中做到这一点。但是在 FutureBuilder 中,由于 whereIn 的限制为 10,我无法获取更多。我知道使用StreamBuilder可以实现,但是我很无奈,不知道怎么做。
这是我的 Firebase 收藏。
下面是获取数据的代码:
final FirebaseFirestore firestore = FirebaseFirestore.instance;
getData() async {
SharedPreferences sp = await SharedPreferences.getInstance();
String _uid = sp.getString('uid');
final DocumentReference ref = firestore.collection('users').doc(_uid);
DocumentSnapshot snap = await ref.get();
List d = snap['loved items'];
List filteredData = [];
if (d.isNotEmpty) {
await firestore
.collection('contents')
.where('timestamp', whereIn: d)
.get()
.then((QuerySnapshot snap) {
filteredData = snap.docs;
});
}
notifyListeners();
return filteredData;
}
这是 FutureBuilder 代码:
body: sb.guestUser == true
? EmptyPage(
icon: FontAwesomeIcons.heart,
title: 'No wallpapers found.\n Sign in to access this feature',
)
: FutureBuilder(
future: context.watch<BookmarkBloc>().getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data.length == 0)
return EmptyPage(
icon: FontAwesomeIcons.heart,
title: 'No wallpapers found',
);
return _buildList(snapshot);
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error),
);
}
return Center(
child: CupertinoActivityIndicator(),
);
},
),
),
);
}
Widget _buildList(snapshot) {
return StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
List d = snapshot.data;
return InkWell(
child: Stack(
children: <Widget>[
Hero(
tag: 'bookmark$index',
child: cachedImage(d[index]['image url'])),
Positioned(
bottom: 15,
left: 12,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
d[index]['category'],
style: TextStyle(color: Colors.white, fontSize: 18),
)
],
),
),
Positioned(
right: 10,
top: 20,
child: Row(
children: [
Icon(Icons.favorite,
color: Colors.white.withOpacity(0.5), size: 25),
Text(
d[index]['loves'].toString(),
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: 16,
fontWeight: FontWeight.w600),
),
],
),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(
tag: 'bookmark$index',
imageUrl: d[index]['image url'],
catagory: d[index]['category'],
timestamp: d[index]['timestamp'],
)));
},
);
},
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 4 : 3),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
padding: EdgeInsets.all(15),
);
}
}
我参考了互联网,但我不完全知道如何将 FutureBuilder 转换为返回快照列表的 StreamBuilder。还有其他方法吗?
【问题讨论】:
标签: flutter dart google-cloud-firestore stream-builder flutter-futurebuilder