首页 > 解决方案 > 列表作为 Json 编码返回最后一个索引值

问题描述

在这里,我已将值添加到 contactList.listChild 但字符串列表不会将所有值返回到父列表它只返回最后添加的值。我知道这是一个简单的错误,但我不知道在哪里犯了错误。

任何建议都会有所帮助。

   ContactName contactList = new ContactName();

  createJson(){

    for(int index = 0; index < _contacts.length; index++){

      Contact contact = _contacts?.elementAt(index);
      List<Item> numbersList = contact.phones.toList();

      for(int i = 0; i < numbersList.length; i++ ){

        contactList.listChild = [numbersList[i].value];
      }

      contactList.name = contact.displayName;

      lisJson.add(contactList.toJson());

    }

    var data = {
      "data" : lisJson
    };

    var body = json.encode(data);
    print("$body");

  }

// here is my model class

class ContactName extends Object {

  String name;
  List<String> listChild = new List<String>();

  Map toJson() => {"name":name, "phone":listChild};
}

这就是我从中得到的

{
  "data": [
    {
      "name": "user1",
      "phone": [
        "8221551458"
      ]
    },
    {
      "name": "user2",
      "phone": [
        "1234567890"
      ]
    }
  ]
}

// and the output should be something like this 

{
  "data": [
    {
      "name": "user1",
      "phone": [
        "8221551458"
      ]
    },
    {
      "name": "user2",
      "phone": [
        "8220780548"
        "1234567890"
      ]
    }
  ]
}

标签: jsonflutterdartencoding

解决方案


你需要更换

contactList.listChild = [numbersList[i].value]

经过

contactList.listChild.add(numbersList[i].value)

您的代码在 for 语句的每次迭代中创建一个新列表,这就是为什么最后一个元素是您看到的唯一元素的原因。

一定要contactList.listChild在使用它之前进行初始化,否则在尝试添加新元素时会抛出异常。


推荐阅读