我正在尝试创建一个FloatingActionButton,以对从Firebase流式传输的List进行洗牌。
Stream<QuerySnapshot> stream =
Firestore.instance.collection('albums').snapshots();
List<DocumentSnapshot> _snapshotList = [];
_shuffleAlbums() {
setState(() {
_snapshotList.shuffle();
});
}
...
StreamBuilder(
stream: stream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: new CircularProgressIndicator(
backgroundColor: Theme.of(context).primaryColor,
),
);
} else {
snapshot.data.documents.forEach((e) {
_snapshotList.add(e);
});
return GridView.builder(
itemCount: snapshot.data.documents.length,
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: tileCount != null ? tileCount.round() : 2,
),
itemBuilder: (context, index) {
return new AlbumTile(
albumModel: Album.fromMap(_snapshotList[index].data),
prefs: prefs,
);
},
);
}
},
),
...
这确实会打乱列表,但也会创建重复项。该列表应该是58个项目(Firebase数据库中的文档数量),但是该列表从116个项目(应该是它的两倍)开始,并且每次我调用shuffle()方法时都会增加58个。我制作了列表的截图,其长度不断增加:https://imgur.com/a/BXW1UFT
我正在拔头发。我认为List的改组方法可以完全满足我的需求。相反,它会创建重复项,并且显然(由于ListView不会显示出来,因此不可见)将项目添加到列表中。其他方法(例如使用随机和循环)也导致重复。这与从Firebase流式传输的DocumentSnapshots列表有关吗?
感谢阅读。
每次调用_shuffleAlbums()
时,setState()
都会触发重建。每次重建时,我都会通过forEach()
方法将快照中的整个列表添加到_snapshotList中。相反,只需_snapshotList = snapshot.data.documents;
就足够了。