0

I have a contact list, where I would like to send the givenName, familyName and displayName to an api using json string..

final contacts =
    (await ContactsService.getContacts(withThumbnails: false)).toList();

I tried but unable to created nested array:

List<dynamic> list = new List<dynamic>();

for (final contact in contacts) {
    list.add(contact.givenName);
}

print(list);

I would like it something like:

[
    {"id":1,"givenName":"Joe","familyname":"Walker"},
    {"id":2,"givenName":"Zoe","familyname":"Sleeper"}
];
1
  • 1
    Can you share contacts list which comes from ContactsService? Commented Aug 4, 2020 at 10:30

1 Answer 1

1

Updated try this one

for (final contact in contacts) {
     var json = {'givenName' : contact.givenName, 'familyName': contact.familyName};
     list.add(json);
 }

OLD

Your Contact class should have a toJson method to do this.

class Contact {
   Int id;
  String givenName, familyName;

  Map<String, dynamic> toJson() =>
  {
    'id': id,
    'givenName' : givenName, 
    'familyName': familyName,
  }; 
}

Now your code should work

List<dynamic> list = new List<dynamic>();

for (final contact in contacts) {
    list.add(contact.toJson());
}

print(list); 
Sign up to request clarification or add additional context in comments.

4 Comments

I am getting errors is it possible class Contact is conflicts with pub.dev/packages/contacts_service package as thats also uses Contact ?
gist.github.com/andraskende/24a26b98fea68424557bad6f34641ea4 the error message is commented, Thank you !
try this one for (final contact in contacts) { var json = {'givenName' : contact.givenName, 'familyName': contact.familyName}; list.add(json); }
Perfect! Thank You !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.