0

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?

1
  • The collection-for construct is used with expressions, not statements, so you can't use braces for it (unless you're trying to create a Set literal, which is how it's being interpreted here). Remove the braces. Commented Mar 2, 2021 at 11:34

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

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.