Search code examples
flutterdartcontacts

contact_services getContactsForPhone returing Future<dynamic> instead of String - Flutter


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


Solution

  • 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.