【问题标题】:contact_services getContactsForPhone returing Future<dynamic> instead of String - Flutter联系服务 getContact ForPhone 返回 Future<dynamic> 而不是 String - Flutter
【发布时间】:2021-06-08 19:58:42
【问题描述】:

我正在尝试使用函数getContactsForPhone 获取Contact

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

但我得到的是Future&lt;dynmaic&gt; 而不是应该是字符串的.displayName

【问题讨论】:

标签: flutter dart contacts


【解决方案1】:

你正在混合使用 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()
  }

应该返回您想要的 DisplayName。

记得在外部使用await关键字,无论你在哪里调用这个函数。

您可以阅读更多关于未来和异步代码here

【讨论】:

  • 嘿,抱歉回复晚了,我完全复制了你的代码,但它仍然返回相同的东西,Future。 @Naslausky
  • @AnanSaadi,我在两点上编辑了我的答案:1)返回类型应该是 Future,2)在调用这个函数时你也需要使用 await
  • 谢谢@Naslausky,它终于可以工作了:D
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2018-09-28
  • 2020-08-15
  • 2021-08-18
相关资源
最近更新 更多