我正在尝试Contact
使用该功能getContactsForPhone
getName()async{
number = '123-456-7890'
return await ContactsService.getContactsForPhone(number).then((value) => value.elementAt(0).displayName.toString());
}
但我得到Future<dynmaic>
而不是.displayName
哪个应该是字符串
你正在混合使用 Futures 的两种方式:
await
关键字来等待结论。then
方法在 Future 结束时进行回调。你需要选择一个并坚持下去。使用await
总是更可取的,因为它使代码更具可读性并避免了一些回调地狱。
在你的情况下:
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()
}
哪个应该返回你想要的 DisplayName。
记住还要await
从外部使用关键字,无论你在何处调用此函数。
你可以在此处阅读有关 Future 和异步代码的更多信息。
嘿,抱歉回复晚了,我完全复制了您的代码,但它仍然返回相同的内容,Future<dynamic>。@纳斯劳斯基
@AnanSaadi,我在两点中编辑了我的答案:1) 返回类型应该是 Future<String>,2)
await
调用此函数时也需要使用。谢谢@Naslausky,它终于起作用了:D