0

I am trying to get Contact using the function getContactsForPhone

   getName()async{
    number = '123-456-7890'
    return await ContactsService.getContactsForPhone(number).then((value) =>  value.elementAt(0).displayName.toString());
  }

but I am getting Future<dynmaic> instead of .displayName which is supposed to be String

Anan Saadi
  • 328
  • 4
  • 21

1 Answers1

2

You are mixing it up two way's to use Futures:

  • You can use await keyword to await for the conclusion.
  • You can use the then method to have a callback when the Future ends.

You need to choose one and stick with it. Using the await is always preferable because it makes the code more readable and avoids some callback hells.

In your case:

Future<String> getName() async {
    number = '123-456-7890'
    Iterable<Contact> myIterable = await ContactsService.getContactsForPhone(number);
    List<Contact> myList = myIterable.toList();
    return myList[0].displayName.toString()
  }

Which should return the DisplayName you wanted.

Remember to also use the await keyword from the outside, wherever you call this function.

You can read more about Future and Asynchronous code here.

Naslausky
  • 3,443
  • 1
  • 14
  • 24
  • Hey, sorry for the late reply, I copied your code exactly but it's still returning the same thing, Future. @Naslausky – Anan Saadi Mar 31 '21 at 10:39
  • @AnanSaadi, I've edited my answer in two points: 1) The return type should be Future, and 2) you need to use the ```await``` when calling this function aswell. – Naslausky Mar 31 '21 at 14:32
  • 1
    Thank you @Naslausky, it's finally working :D – Anan Saadi Mar 31 '21 at 15:42