Reputation: 115
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?
Upvotes: 0
Views: 3803
Reputation: 4499
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();
Upvotes: 2