Reputation: 386
I am new to Flutter, and I'm trying to read and write data to a Firestore document when a QR code is scanned. I have been able to write data to my Firestore document, but I can't figure out the proper syntax to read data from the document. All the answers I've seen online use StreamBuilder to return values to a Text view, but I just need the values to use in my function, not show on the app screen.
Here's my code:
class _MyAppState extends State<MyApp> {
String result="";
Future _scanQR() async{
String cameraScanResult = await scanner.scan();
DateTime now = new DateTime.now();
setState(() {
result=cameraScanResult;
DocumentReference document = FirebaseFirestore.instance
.collection('coin_tracker')
.doc(result);
var num_of_uses = document.snapshots()['number_of_uses'];
document.update({
'checkout_date': Timestamp.fromDate(now),
'number_of_uses': num_of_uses+1,
});
});
}
The above worked fine to update the checkout_date based on the QR scan. But I can't figure out how to get the 'number_of_uses' value from the document to then add on to.
The document looks like this:
'1000000001' {
'checkout_date: October 4, 2020 at 4:43:22 PM UTC-6,
'number_of_uses':0,
}
Upvotes: 0
Views: 91
Reputation: 317467
You probably just want to use get() for a one-time read that returns Future, as illustrated in the documentation.
DocumentReference reference = FirebaseFirestore.instance
.collection('coin_tracker')
.doc("the-doc-id");
DocumentSnapshot snapshot = await reference.get();
int number_of_uses = snapshot.get("number_of_uses");
Upvotes: 1