有没有一种方法可以随机化来自Firestore的数据?我正在使用streambuilder和staggeredview.countbuilder。我找不到有关它的任何文档!现在,数据按流的最后注册顺序进入。 有人可以帮忙吗? 致以最诚挚的问候
这是我的代码
StreamBuilder(
stream: Firestore.instance.collection('users').where('myCity', isEqualTo: city).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading');
return Container(
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
User user = User.fromDoc(snapshot.data
.documents[index]);
return GestureDetector(
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(12))
),
child: ClipRRect(
borderRadius: BorderRadius.circular(21),
child: Image.network(user.profileImageUrl,fit: BoxFit.cover,)
),
)
);
},
staggeredTileBuilder: (index){
return StaggeredTile.count(0, index.isEven? 1.2 :1.4);
},
),
);
},
);
答案 0 :(得分:2)
您可以使用List
类的shuffle()方法
每当流发出新值时,它就会洗牌。
class MyApp extends StatelessWidget {
@override
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: StreamBuilder(
stream: Firestore.instance
.collection('users')
.where('myCity', isEqualTo: city)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading');
final docs = snapshot.data.documents..shuffle();
return Container(
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
itemCount: docs.length,
itemBuilder: (BuildContext context, int index) {
User user = User.fromDoc(docs[index]);
return GestureDetector(
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(12))),
child: ClipRRect(
borderRadius: BorderRadius.circular(21),
child: Image.network(
user.profileImageUrl,
fit: BoxFit.cover,
),
),
),
);
},
staggeredTileBuilder: (index) {
return StaggeredTile.count(0, index.isEven ? 1.2 : 1.4);
},
),
);
},
),
),
);
}
}