简体   繁体   中英

How to append data inside loop in list in Flutter dart?

I'm new to flutter dart language. I'm trying to insert a search widget for that I need to create a list containing all JSON values parsed from an external API call. I was able to fetch data from API but I couldn't figure out a way to append this dynamic data inside a constructor class that I created to parse individual values.

output data from API which I receive looks like this

  [{name: nikhil, uploadID: dfkjakds1213}, {name: nikhil, uploadID:
     dfkjakds1213}, {name: nikhil, uploadID: dfkjakds1213}, {name: nikhil,
     uploadID: dfkjakds1213}, {name: nkks, uploadID: szjxb771}, {name:
     nkks, uploadID: szjxb771}...]

now i want to add this 2-d list into myclass list, i can't figure out how to do that? myclass list looks like this, with static data

List<myclass> words = [
    myclass("nikhil", "adnfk"),
    myclass("john", "asdfadsf"),
    myclass("smith", "adf"),
    myclass("stuart", "asdfdf"),
  ];

i want to make make it dynamic using some loops or something, like this

class myclass {
          String name;
          String uploadid;
        
          myclass(this.name, this.uploadid);
        }
getvalue() {
        AuthService().getallStaff("staff", "all").then((val) {
          
         List<myclass> words = [
            for (var item in val.data)
              {
                myclass(item['name'], item['uploadid']),
              }
          ];
        });
    
      }

but I get this error

 The element type 'Set<myclass>' can't be assigned to the list type 'myclass'

How can I fix this?

The for loop inside an array is not allowed to use {} . It will turn items => one set of items .

The result of your case will become A set of myclass in an array:

List<myclass> words = [
  {
    myclass("nikhil", "adnfk"),
    myclass("john", "asdfadsf"),
    ...
  }
]

You can just remove the { } :

List<myclass> words = [
  for (var item in val.data)
    myclass(item['name'], item['uploadid']),
];

or use map (1-to-1):

List<myclass> words = val.data.map((item)=>myclass(item['name'],item['uploadid'])).toList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM