Home > Software engineering >  Flutter(Dart) - How to read from a list in a list?
Flutter(Dart) - How to read from a list in a list?

Time:10-02

So I have data in this format:

List users = [
  {
   "id": "p1",
   "name": "John Doe",
   "age": "44",
   "imageUrl": [
   {
    "assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
    "assets/images/anastasia-vityukova-unsplash.png",
  }
 ],
 "profession": "Financial Consultant"
 },

{
 "id": "p2",
 "name": "John Doe2",
 "age": "42",
 "imageUrl": [
  {
    "assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
    "assets/images/good-faces-hiba-unsplash.jpg",
  }
 ],
 "profession": "Financial Consultant"
 },
];

How do I read the imageUrls?

            decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage(lstUsers[index]["imageUrl"][0]),
              fit: BoxFit.cover),
        ),

enter image description here

CodePudding user response:

As the error says, Dart is treating that field as a Set {} or more specifically as a LinkedHashSet. A set does not implements the [] operator but you could access its elements using the method elementAt.

lstUsers[0]["imageUrl"][0].elementAt(1)

Up until lstUsers[0]["imageUrl"][0] you have selected the first element inside the array, but note that the array its not just made of strings, is one set with the strings inside it.

[{    "assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
    "assets/images/anastasia-vityukova-unsplash.png",  }]

Thats the reason you then have to use .elementAt() to access the strings. I would recommend if its in your power to drop the {} arount the strings so theyre easier to access. Or even better create classes that manage the serialization and deserialization of the JSON. A nice place to start is quicktype.

CodePudding user response:

You can see that the imageUrl array is structured like that:

"imageUrl": [
  {
    "assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
    "assets/images/good-faces-hiba-unsplash.jpg",
  }
],

The first item in the imageUrl array is not a String its a Set (Because it's surrounded with curly braces). If you want to access the first asset in the imageUrl list remove the curly braces and make the imageUrl look like that:

"imageUrl": [
    "assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
    "assets/images/good-faces-hiba-unsplash.jpg",
],


// Now when you use that it will return a String
lstUsers[index]["imageUrl"][0];

If you want to keep the structure of the list the same way and you still want to access the first imageUrl you can use the following syntax:

lstUsers[index]["imageUrl"][0].first;
  • Related