I'm just beginning to use firestore, and in the same time learning to use flutter and dart. I have two widgets : a stateless one and a stateful one, both returning the age of a user in a collection 'users'. The stateless one has the user id as argument, but cannot handle real time changes. I don't know how to modify the stateful one, which does handle real time changes, so that it takes the user id as argument as well. The stateless one :
class GetAge extends StatelessWidget {
final String documentId;
const GetAge(this.documentId);
@override
Widget build(BuildContext context) {
CollectionReference users =
FirebaseFirestore.instance.collection('Users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return const Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return Text('Age : ${data['age']} €');
}
return const Text("loading");
},
);
}
}
The statefull one :
class getAgeRT extends StatefulWidget {
const getAgeRT({super.key});
@override
State<getAgeRT> createState() => _getAgeRTState();
}
class _getAgeRTState extends State<getAgeRT> {
@override
Widget build(BuildContext context) {
return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('Users')
.doc('User1')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> 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(" age : ${data['age']} ");
});
}
}
I tried to copy the stateless one's model to the stateful one but with no success... I don't think it's related to firestore, just a lack of practice from me ! thanks in advance !
The StatefulWidget can receive args too.
class getAgeRT extends StatefulWidget {
const getAgeRT({required this.documentId, super.key});
final String documentId;
@override
State<getAgeRT> createState() => _getAgeRTState();
}
class _getAgeRTState extends State<getAgeRT> {
@override
Widget build(BuildContext context) {
return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(widget.documentId)
.snapshots(),
...
}
You can access the args with widget.
before