I am trying to run a query on my Firebase Firestore data and display the results as a list. Typically, when I do this, I use a streambuilder
, which updates the results whenever any data is changed. I was wondering how to display the same data only once, without subscribing to a stream. This is my code for the streambuilder
, which updates on change.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('announcements')
.orderBy('date', descending: true)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshots) {
if (snapshots.connectionState == ConnectionState.active &&
snapshots.hasData) {
return ListView(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
children: snapshots.data!.size == 0
? [
const Padding(
padding: EdgeInsets.only(top: 10),
child: Text(
"You have no announcements",
style: TextStyle(
height: 1.0,
fontFamily: "urwmedium",
color: Color(0xffD5D6D7),
fontSize: 20,
),
),
),
]
: snapshots.data!.docs.map(
(DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Text(
data['announcementTitle'],
);
},
).toList(),
);
}
return Center(
child: CircularProgressIndicator(
color: CustomColors.textColor,
),
);
},
),
The above code works, but again, it loads information realtime. What would the code be if I wanted it to only load once at opening?
as the StreamBuilder
is helpful in order to get stream of your collection snapshots
to get that data only once, use FutureBuilder
instead:
FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance
.collection('announcements')
.orderBy('date', descending: true)
.get(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshots) {
if (snapshots.connectionState == ConnectionState.done &&
snapshots.hasData) {
return ListView(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
children: snapshots.data!.size == 0
? [
const Padding(
padding: EdgeInsets.only(top: 10),
child: Text(
"You have no announcements",
style: TextStyle(
height: 1.0,
fontFamily: "urwmedium",
color: Color(0xffD5D6D7),
fontSize: 20,
),
),
),
]
: snapshots.data!.docs.map(
(DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Text(
data['announcementTitle'],
);
},
).toList(),
);
}
return Center(
child: CircularProgressIndicator(
color: CustomColors.textColor,
),
);
},
),