如何限制来自Firestore的数据



我想显示来自firebase firestore的最新数据。我只要最新的3份文件。我确实尝试了ListView中的ItemCount,但它不起作用,它也崩溃了应用程序。任何帮助都将非常感激。提前感谢,抱歉大括号stackOverflow不接受我的问题,如果它不像我的代码那么长。

class NewInHouses extends StatefulWidget {
const NewInHouses({Key? key}) : super(key: key);
@override
State<NewInHouses> createState() => _NewInHousesState();
}
class _NewInHousesState extends State<NewInHouses> {
final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('houseRent').snapshots();
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
return Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 160,
width: 2000,
color: Colors.white.withOpacity(0),
child: ListView(
scrollDirection: Axis.horizontal,
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Padding(
padding: const EdgeInsets.fromLTRB(0, 2.5, 10, 2.5),
child: Container(
height: 150,
width: 300,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: [
BoxShadow(
color: Colors.grey,
spreadRadius: 1,
blurRadius: 1,
)]),
child: Row(
children: [
Container(
width: 150,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(5),
bottomLeft: Radius.circular(5),),
image: DecorationImage(
image: CachedNetworkImageProvider(
data["1stpic"],),
),),),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
data["rooms"] +
" Beds  " +
data["baths"] +
" Baths",
style: TextStyle(
fontFamily: "eng",
fontWeight: FontWeight.bold,
color: Colors.blue.shade900,
fontSize: 12),
),],),),],),),);}).toList(),),),);}, ); }}

代替

final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('houseRent').snapshots();

final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('houseRent').orderBy('your-field-name', descending: true).limit(3).snapshots();

你可以在.collection('houseRent').orderBy('insert-field-here')之后添加一个.limit(3),你可以下降它,所以最后一个在顶部

最新更新