0

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,
}
Rushwin Jamdas
  • 344
  • 1
  • 5
  • 18

1 Answers1

1

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");
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks for your response. When I add "await" I get the warning: The await expression can only be used in an async function. – Rushwin Jamdas Oct 05 '20 at 00:35
  • await can only be used inside an async function. If you're not inside an async function, you will need to find another way to handle the asynchronous result of the future. I strongly suggest learning how to use futures in order to be effective at developing flutter apps. https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it – Doug Stevenson Oct 05 '20 at 00:42