How to store the value retrieved from Firebase into a variable Flutter

I'm trying to retrieve the data(customer name, customer ID)from the firebase and store it into the variables. After that, I want to store the variables data into another firebase path location.

I'm able to call the snapshot and print it but I just can't save the data from firebase into the variables.

CollectionReference orderInfo =
      FirebaseFirestore.instance.collection('orderInfo');
  final user = FirebaseAuth.instance.currentUser;
  String cusName;
  String add;

  void getNameAddress() async {
    final doc = await FirebaseFirestore.instance
        .collection('users')
        .doc(user.uid)
        .get();

    cusName = doc['name'];
    add = doc['address1'] + '' + doc['address2'] + '' + doc['address3'];
  }

  Future initializeOrder(BuildContext ctx) {
    getNameAddress();
    return orderInfo.doc(user.uid + 'order').set({
      'orderID': '',
      'cusID': user.uid,
      'cusName': cusName,
      'cusAdd': add,
      'clID': '',
      'clName': null,
      'price': null,
      'selectedDate': null,
      'serviceSelected': null,
      'typeOfService': 'Not selected yet',
    });
  }

The intializeOrder() is the function that I use to store the data in another path.

How should I solve it ?

1 answer

  • answered 2021-07-27 16:57 Renaud Tarnec

    Since the getNameAddress() function is async and the Firestore set() method is asynchronous, you need to make your initializeOrder() function async and use await when calling getNameAddress(), as follows:

      Future<void> initializeOrder(BuildContext ctx) async {
        await getNameAddress();
        return orderInfo.doc(user.uid + 'order').set({
          'orderID': '',
          'cusID': user.uid,
          'cusName': cusName,
          'cusAdd': add,
          'clID': '',
          'clName': null,
          'price': null,
          'selectedDate': null,
          'serviceSelected': null,
          'typeOfService': 'Not selected yet',
        });
      }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum