Home > other >  Function that returns a value from firestore in flutter
Function that returns a value from firestore in flutter

Time:09-05

Hey guys so I need to get a field value from the firestore in order to use it in my code for some reason I created this method to get the value for me but it always returns Instance of 'Future' even though the field I'm returning is a String anyone know what is the issue here

getTheNextUserId() async{
var collection = FirebaseFirestore.instance.collection('collId');
var docSnapshot = await collection.doc('dId').get();
if (docSnapshot.exists) {
  Map<String, dynamic> data = docSnapshot.data()!;
  var uId = data['nextUserId'];
  return uId;
}
Future addUserDetails(String firstName, String lastName, int age,String email) async {
  final CollectionReference userRef = FirebaseFirestore.instance.collection('user');
  await userRef.doc(getTheNextUserId.toString()).set({
  'first name': firstName,
  'last name': lastName,
  'age': age,
  'email': email,
  'count': 10,});

}

CodePudding user response:

Your getTheNextUserId is an async function, so it also must be awaited:

Future addUserDetails(String firstName, String lastName, int age,String email) async {
  final CollectionReference userRef = FirebaseFirestore.instance.collection('user');
  await userRef.doc(await getTheNextUserId.toString()).set({ // in this line
    'first name': firstName,
    'last name': lastName,
    'age': age,
    'email': email,
    'count': 10,
});

CodePudding user response:

Instead of this:

final CollectionReference userRef = FirebaseFirestore.instance.collection('user');

do this:

final CollectionReference userRef = await FirebaseFirestore.instance.collection('user');

You have to await for async value in order to get its value.

  • Related