contact_services getContactsForPhone 返回 Future<dynamic> 而不是 String - Flutter

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

我正在尝试使用函数 getContactsForPhone

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

但我得到的是 Future<dynmaic> 而不是 .displayName 应该是 String

您正在混合使用 Futures 的两种方式:

  • 您可以使用await关键字等待结论。
  • 您可以使用then方法在Future结束时进行回调。

你需要选择一个并坚持下去。使用 await 总是可取的,因为它使代码更具可读性并避免一些 callback hells.

你的情况:

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()
  }

哪个 return 您想要的显示名称。

请记住,无论在何处调用此函数,都要从外部使用 await 关键字。

您可以阅读更多关于 Future 和异步代码的内容 here