【发布时间】:2020-06-29 06:25:39
【问题描述】:
我正在使用这个package 来检索设备的联系人。该库检索 427 个联系人,我想循环整个列表,以便我可以创建另一个列表并将其发送到后端。问题是循环不起作用,这个函数在循环完成之前返回。
这里是我使用的函数:
Future<QueryResult> uploadContacts() async {
final List<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
List<ContactInput> contactsListInput;
print('contactsListInput length: ${rawContacts.length}');
rawContacts.forEach((contact) {
print('contact: $contact'); //PRINTED JUST ONCE
//Contact can have more than 1 number. We need them all
contact.phones.forEach((phone) {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
print('contactsListInput length: ${contactsListInput.length}'); //NEVER PRINT ANYTHING
final ContactsListInput input =
ContactsListInput(contacts: contactsListInput);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
我也尝试过使用 for 循环,同样的事情发生了。
for (int i = 0; i < rawContacts.length; i++) {
final contact = rawContacts[i];
final contactInput =
ContactInput(name: contact.displayName, phone: contact.phones.first.value);
contactsListInput.add(contactInput);
}
print('contactsListInput length: ${contactsListInput.length}'); //NEVER CALLED
我也尝试过 Future.forEach
await Future.forEach(rawContacts, (contact) async {
print('contact: $contact');
//Since contact can have more than one number we loop them too.
await Future.forEach(contact.phones, (phone) async {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
如何解决这个问题?任何帮助将不胜感激。
【问题讨论】:
-
List<ContactInput> contactsListInput;是null- 当contactsListInput为空时,您不能调用contactsListInput.add(contactInput);- 您必须初始化该列表 - 顺便说一句,您不需要那些forEach/add等 -只需使用Iterable.map()/Itarable.expand()方法 -
在我看来,您的
contactsListInput列表从未初始化为值。您可能会遇到异常 -
就这么简单:
rawContacts.expand((contact) => contact.phones.map((phone) => ContactInput(name: contact.displayName, phone: phone))) -
正如我所说:您根本不需要该列表(以及两个
forEach循环):只需使用expand()/map()方法 -
很好,然后发布一个自我回答