How to use the value of a Future in flutter

Asked

Viewed 785 times

0

I’m using Flutter to create a mobile app with two collections in the Cloud Firestore, the collection user and the collection person.

  • The collection person stores the information of all persons who can register in the app.
  • The collection user stores the date of the registered user.

I want to use the information inside the collection documents user to search for a document in the collection person. After the user registers I cannot use the user name to perform a query in the collection person.

Future<String> getPersonName(userId) {
  Firestore.instance
      .collection('user')
      .document(userId)
      .get()
      .then((DocumentSnapshot ds) {
  return  ds['Person Name'];
  }, onError: (error) {
    return error;
  }

  );
}

Future<String> getPersonData(personName, documentData) async {
  DocumentSnapshot snapshot = await Firestore.instance
      .collection('person')
      .document(userId)
      .get();
  var name= snapshot.data[documentData];
  if (name is String) {
    return name;
  } else {
    return 'Empty';
  }
}

The function getPersonName() returns a Future with the value I want to use in the function getPersonData()

In my Scaffold I used a FutureBuilder to display the date.

    FutureBuilder(
        future: getPersonData(personName, 'Data'),
        builder: (context, snapshot) {
          return Text(snapshot.data);
        }),

The Future returns the correct information

In the FutureBuilder how can I access the value of personName? I’ve tried several options and I always end up with a Future instead of the value.

  • 1

    Where is the line you call the function getPersonName()?

  • You seem to be new on the site... So a tip, don’t pollute the same with multiple questions, you could just EDIT your other question here!

1 answer

1

You always get the Future because you are not returning the data correctly, in your method getPersonData() you did right the use of async, you just need to pack yours getPersonName() accordingly...

Modify as follows:

Future<String> getPersonName(userId) async {
  DocumentSnapshot document = await Firestore.instance
      .collection('user')
      .document(userId)
      .get();

    return  document['Person Name'];
  );
}

Observing

How you didn’t tell us where and how the method is used getPersonName() I can’t advise you the best way to use the method after the modification I suggested, so then you make the necessary adjustments.

But when using it, to get the value without Future, you will have to make the call like this

Future<void> seuMetodo() async {
  String personName = await getPersonName(idPessoa);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.