My Code is working but there is a problem it runs 4 times I think problem is Document number. In Firebase Firestore I have 4 document but i need to use only one at a time. So How can i do this. I found some solutions but all of them old their code doesn't work, it seems to be changed. Here is the full code:
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('catanR').snapshots();
height = MediaQuery.of(context).size.height;
width = MediaQuery.of(context).size.width;
return StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Container(
color: Colors.white,
child: Center(
child: Text(
'Something went wrong',
style: TextStyle(fontFamily: 'Cairo', fontSize: 24),
),
),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(),
),
);
}
return Material(
child: ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
return Container( // THİS PART DOESN'T MATTER
Actual Output is like this:
However, when I scroll because of the StreamBuilder and the document number, that number of screens appears. And as you guessed i just only need one without scrolling.
If you want to build it once, don't return a ListView and its children generated from the collection's docs, just return the container with the data[index] you want to use.
null safety
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore
.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid) // 👈 Your document id change accordingly
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
Map<String, dynamic> data =
snapshot.data!.data()! as Map<String, dynamic>;
return Text(data['fullName']); // 👈 your valid data here
},
),
),
);
}
Also refer: How to use StreamBuilder
and FutureBuilder
for single and multiple documents
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.